Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Functions

in C++

COMP315
2024
1
Introduction to Functions
• A complex problem is often easier to solve by dividing it into
several smaller parts, each of which can be solved by itself.
• This is called structured programming.
• These parts are sometimes made into functions in C++.
• main() then uses these functions to solve the original
problem.

2
Procedural-based Programming
• Every C++ program contains (starts with) a main() function.
• The main() function may in turn call other user defined functions
• Functions encapsulates an algorithm which operates on data
passed in as parameters or explicit access to globally scoped data
• An object’s scope determines its visibility (where it can be used)
• C++ defines several useful facilities related to functions:
–overloaded function definitions
–function prototypes
–exceptions
–STL and generic algorithms
3
C++ Functions
• C++ allows the use of both internal (user-defined) and external
functions.

• External functions (e.g., abs, ceil, rand, sqrt, etc.) are usually grouped
into specialized libraries (e.g., iostream, stdlib, math, etc.)

4
Functions
• Functions are fundamental building blocks in C++
• Functions break up complex tasks into many smaller tasks

5
Function Definition
A Function Definition defines a function, and provides the implementation of the function

double abs(double x)
{
if(x >= 0)
{
return x;
}
else
{
return –x;
}
}
6
Function Definition
A Function Definition defines a function, and provides the implementation of the function

Return type double abs(double x)


{
if(x >= 0)
{
return x;
}
else
{
return –x;
}
}
7
Function Definition
A Function Definition defines a function, and provides the implementation of the function

Return type double abs(double x)


{
if(x >= 0)
{
Function name return x;
}
else
{
return –x;
}
}
8
Function Definition
A Function Definition defines a function, and provides the implementation of the function

Return type double abs(double x)


{
Parameter type
if(x >= 0)
{
Function name return x;
}
else
{
return –x;
}
}
9
Function Definition
A Function Definition defines a function, and provides the implementation of the function

Return type double abs(double x)


{
Parameter type
if(x >= 0)
{
Function name return x;
}
Parameter name
else
{
return –x;
}
}
10
Function Definition
A Function Definition defines a function, and provides the implementation of the function

Return type double abs(double x)


{
Parameter type
if(x >= 0)
{
Function name return x;
}
Parameter name
else
{
return –x;
} Return a value of the same
} type as the function
declaration provided 11
Why use functions?
• Turn computations that can be reused into functions - this reduces
redundancy
• Functions can be reused, and this saves programming time, and
reduces the amount of code
• Functions ensure uniformity - it reduces the risk of calculation errors
by redefining the same algorithms or calculations for each use

12
Prototype (or Function Declaration)

Prototypes are an “advertisement ” that promises that the function is


implemented elsewhere, either later in the current file, or later in a
separate file

• Remember from earlier, Function Definitions are followed by a {…}


block, but Prototypes just end in a semicolon ; and Prototypes have
no implementation block
• Prototypes declare a function so that it can be called before it is
defined

13
Prototypes in a .cpp file
// #include directives

// Prototype or Function declaration;

// main () {… call prototype…}

// Define Prototype function

14
Prototypes in a .cpp file
#include <iostream>
#include <cmath>
using namespace std;

// Declaration of future_value
double future_value(double initial_balance, double p, int n);

int main()
{
...
// Use of future_value
double balance = future_value(1000, rate, 5);
...
}

// Definition of future_value
double future_value(double initial_balance, double p, int n)
{
double b = initial_balance * pow(1 + p / 100, n);
return b;
} 15
Why use Prototypes?

It makes code easier to read – you can first read the main function,
and then the helper functions

• The need for this will become most apparent when you are dealing
with multiple functions, and classes

• There is a disadvantage to prototypes – if you want to change the


name of the function, you need to change it in the declaration, its
calls, and the definition

16
We’ll use an analogy to understand this better
• Let the main function be a waiter
• The waiter’s job is to record your order
(user input), and to send your call to the
kitchen (calls other functions)
• The waiter delivers your meal from the
kitchen (returns an output from the
function)

17
Analogy continued
• The Prototype is the menu
• The menu only provides the you with
the necessary information that you
need. It does not include a step-by-
step recipe of your dish
• Likewise, the prototype does not
define the function, it merely states
that the function exists.

18
Analogy continued
• The Function Definition can be thought of as
the recipe of the dish ordered
• It provides substance, and implementation
• As the customer, you simply need to know
what is on the menu, the waiter records your
order and sends it to the kitchen, the kitchen
prepares the dish that you selected from the
menu, and provides you with the finished
dish (it returns a result)

19
20
Inline Functions
• An inline function is a function in which the function code replaces
the function call directly
• Sometimes the function body is very short, and the execution time
involved in the function call is greater than the execution time
required by the body
• When an inline function is invoked, the complier expands the body of
the function, therefore eliminating the execution cost of the function
call
• Typically inline functions have 3 or fewer assignment statements, or a
single if statement, and/or a single return statement, and no loops or
recursion. Generally longer bodies, should be a regular function
21
Inline Function syntax
Inline functionName
{
…function body…
}

22
Inline Function example
#include <iostream>
using namespace std;

inline int cube(int s)


{
return s*s*s;
}

int main()
{
cout << "The cube of 2 is: " << cube(2) << endl;
return 0;
}
23
Value Parameters
A value parameter is a variable that is initialised with a value supplied by the caller

int main()
{
int x = 0;
int funct(int temp)
cout<<funct(x)<<endl; //outputs 1
{
cout<<x<<endl; //outputs 0 as funct() does not change the x value
temp = temp + 1;
return temp;
int y = 7;
}
cout<<funct(y)<<endl; //outputs 8
cout<<y<<endl; //outputs 7 as funct() does not change the y value
}

24
Value Parameters
A value parameter is a variable that is initialised with a value supplied by the caller

int main()
int funct(int temp)
{
{
int x = 0;
temp = temp + 1;
cout<<funct(x)<<endl;
return temp;
cout<<x<<endl;
}
}

x: 0

temp: 0
Copies the value
25
Value Parameters
A value parameter is a variable that is initialised with a value supplied by the caller

int main()
int funct(int temp)
{
{
int y = 7;
temp = temp + 1;
cout<<funct(y)<<endl;
return temp;
cout<<y<<endl;
}
}

y: 7

temp: 7
Copies the value
26
Reference Parameters

A reference parameter denotes a reference to a variable that is supplied in a function call.

• It is used to define a variable that is bound to a variable in the


function call, to allow the function to modify the variable
• It therefore, updates a variable that was supplied in the method call
• The & symbol is used for referencing
• Syntax
type & parameterName

27
Reference Parameters
• The & symbol is used for referencing, for the sake of understanding, the same example
used for value parameters (slide 22) is used below, to illustrate the difference:
int main()
{
int x = 0; int funct(int &temp)
cout<<funct(x)<<endl; //outputs 1 {
cout<<x<<endl; //outputs 1 as funct() changed the value of x temp = temp + 1;
return temp;
int y = 7; }
cout<<funct(y)<<endl; //outputs 8
cout<<y<<endl; //outputs 8 as funct() changed the value of y
}
1st call, refers to x
x: 0

temp:
y: 7
2nd call, refers to y 28
Reference Parameters
Advantage
• Pass by value copies all values into the function parameters, this can
be very costly especially if the function is large. Pass by reference
avoid this penalty as a reference is created to the actual arguments.
This avoid copying, and runs in minimal time.
Disadvantage
• References allow the function to change the value of the argument,
which is undesirable when we want an argument be read-only. If we
know that a function should not change the value of an argument,
but don’t want to pass by value, the best solution is to pass by const
reference.
29
Constant Reference Parameter
• Const type &parameterName

void funct(const int &x) // x is a constant reference


{
x=6; // compile error, as a const reference cannot have its value changed
}

30
Guidelines for passing variables
• Use call-by-value for very small objects
• Use call-by-const-reference for large objects
• Return a result rather than modify an object through a reference
argument
• Use call-by-reference only when you have to

31
Variable Scope

The scope of a variable is the part of the program in which it is visible.

• Local variable: Variables that are defined inside functions


• Global variable: Variables that are defined outside a function, visible
to all functions defined after it.
• Try to minimise the use of global variables by using parameters and
classes

32
Scope Resolution Operator
• The scope resolution operator :: has many purposes –

1. To access a global variable when there is a local variable with


same name
2. To define a function outside a class
3. To access a class’s static variables
4. In case of multiple Inheritance
5. For namespace
6. Refer to a class inside another class

33
Accessing global and local variables with ::
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x << endl;
cout << "Value of local x is " << x << endl;
return 0;
}

34

You might also like