You are on page 1of 26

Chapter Two

C++ Functions
Contents
• Function declaration, definition…
• Function parameters and arguments
• Pass by value and reference
• Return by value and reference
• Inline functions
• Friend functions
• Overloaded functions
• Recursive functions
Introduction to
• A functionfunctions
is a computational recipe (formula), designed to
tackle a specific problem which aids in the conceptual
organization of a program.
• A function stored in one place in memory can be invoked
from different sections of a program
• C++ functions generally adhere to the following rules.
Every function must have a name assigned by a
programmer.
Function names can contain up to 32 characters, begin with
a letter, can consist of letters, numbers, and underscore
character.
All function names have one set of parenthesis immediately
following them.
ReturnType Name ( parameter1,
The body of each function
parameter2, ...) must be enclosed by braces.
• Syntax: { statements } 3
Declaring, defining and calling
functions
• Declaring function (Prototyping):
Function declarations, also called prototypes, provide a
model or blueprint for the function.
They tell the compiler, “a function that looks like this is
coming up later in the program”
The interface of a function (also called its prototype)
specifies how it may be used. It consists of three
entities:
 The function return type. This specifies the type of
value the function returns.
The function name. this is simply a unique identifier
The function parameters (also called its signature). 4
Defining a function
• A function definition consists of two parts: interface
(prototype) & body.
• The brace of a function contains the computational
steps (statements).
• The definition consists of a line (first line of the
definition) called the declarator.
• If function definition is done before the main function,
then there is no need to put the prototype, otherwise
the prototype should be scripted before the main
function starts.

5
Calling the function
• Calling a function means making the instruction of the
function to be executed.
• The syntax of the call is very similar to that of the
declaration, except that the return type is not used.
• A function call consists of the function name followed by
the call operator brackets ‘()’, inside which zero or more
comma-separated arguments appear.
• When a function call is executed, the arguments are first
evaluated and their resulting values are assigned to
the corresponding parameters.
• The function body is then executed. Finally the return
value (if any) is passed to the caller. 6
Example

7
Function Parameters and
arguments
• A function parameter (formal parameter) is a
variable declared in the function declaration. It is a
receiving variable.
• Argument (actual parameter) is a value that is
passed to the function by the caller.
• The arguments of a function calling can be passed
either passing by value or passing by reference
Passing by value:
• A function parameter receives a copy of only the value
of the argument.
• As a result, if the function makes any changes to the
parameters, this will not affect the argument. 8
Example:
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
9
Passing by Reference
• A reference parameter receives the address of the
argument
• The variable itself is passed to the function
• Any change made to a reference parameter directly
affects argument.
• In passing by reference, in function declaration the type
of each parameter must be followed by an ampersand
sign (&).
• This ampersand specifies that corresponding arguments
are to be passed by reference

10
Example: pass by reference

• The above function modifies parameters a,


b and c, correspondingly, values of x, y and
z is also modified.
• Passing by reference is also an effective
way to allow a function to return more than 11
Return by Value and By
Reference
Return by Value
• A copy of value is returned to the caller.
Example:
int doubleValue(int x)
{
    int value = x * 2;
    return value ; // A copy of value will be returned here
} // value goes out of scope here

12
Return by value…
• When to use return by value:
To return variables declared inside the function
To return arguments that were passed by value
• When not to use return by value:
To return pointer (use return by address)
To return a large struct or class (use return by
reference)

13
Return by Reference

• The return type of function test() is int& include <iostream>


using namespace std;
• The return statement is return n; it returns
int n;
variable n itself. int& test();
• Then the variable n is assigned to the left int main()
side of code test() = 5; and value of n is {
displayed test() = 5;
• Similar to pass by reference, values cout<<n;
returned by reference must be variables return 0;
• Return by reference is also fast, which can }
 int& test()
be useful when returning structs and
{
classes.
return n;
}

14
Consider the following example:
• Don’t return local variables to the function
by reference.
int& doubleValue(int x)
{
    int value = x * 2;
    return value; // return a reference to
value here
• valueshould be ais global
} // value destroyedvariable
here
• Return by reference is used to return
arguments passed by reference

15
Global vs local variables
• The scope of variables declared within a
function or any other inner block is only
their own function or their own block and
can not be used outside of their block.

16
Scope Operator
Int num1;
• A local scope overrides the Void fun1(int num1)
{
global scope //…..
}
• The global num1 is
int num1 = 2;
inaccessible inside fun1(), void fun1(int num1)
because it is overridden by the {
//…
local num1 parameter num1=33;
• This problem is overcome cout<<num1; /* the
output will be 33 */
using the scope operator ‘::’ cout<<::num1; /*the
which takes a global entity as output will be 2 which is
the global */
argument. if(::num1 != 0)//refers to
global num1
//…
} 17
Inline functions
• The compiler places a copy of the code of that
function at each point where the function is
called at compile time.
• Compiler replaces the definition of inline
functions at compile time instead of referring
function definition at runtime. 
• Suppose that a program frequently requires
finding the absolute value of an integer quantity.
For a value denoted by n
(n > 0 ? n : -n)
• However, instead of replicating this expression in
many places in the program, it is better to define
it as a function:
int Abs(int n) 18
Inline functions…
• The function version has a number of advantages.
It leads to a more readable program.
It is reusable.
The disadvantage of the function version, however is
that
Its frequent use can lead to considerable performance
penalty due to overheads associated with calling a
function.
• The overhead can be avoided by defining Abs as an
inline function.
inline int Abs(int n)
{ 19
Inline functions…
• Every function can not be inlined.
• the function calls itself, that is recursive
• the function contains loops such as for(;;) or while()
• the function size is too large
• Most of the advantage of inline functions comes from
avoiding the overhead of calling an actual function.
• Such overhead includes saving registers, setting up
stack frames, and so on.
• But with large functions the overhead becomes
less important.

20
Friend Function
• If a function is defined as a friend function then, the
private and protected data of class can be accessed
from that function.
• The complier knows a given function is a friend function
by its keyword friend.
• The declaration of friend function should be made inside
the body of class (can be anywhere inside class either in
private or public section).

21
Example
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=5; //accessing private data 22
Overloaded Functions
• Unlike C, C++ lets you have more than one
function with the same name.
• Functions with the same name are called
overloaded functions.
• C++ requires that each overloaded functions
differs in its argument list.
• Overloaded functions enable you to have similar
functions that work on different types of data.
• Two functions can have same identifier(name) if
either number of arguments or type of arguments
passed to functions are different.
• These types of functions having similar name are
called overloaded functions. 23
Example:

int abs(int i);


float abs(float x);
int main()
{
ians = abs(i);//calling
abs with int 24
Recursive function
• A function which calls itself is said to be recursive.
• Recursion is a general programming technique
applicable to problems which can be defined in terms of
themselves.
• Example: the factorial problem
int factorial(unsigned int n )
{
return n = = 0 ? 1 : n * factorial(n-1);
}
• A recursive function must have at least one termination
condition which can be satisfied.
• Otherwise, the function will call itself indefinitely until 25
Exercise
1.Write a C++ function that returns the number of times
a given number n is divisible by two. For example the
umber 16 is divisible by two four times, 6 is divisible by
2 only once….and so on.
2. Write a c++ function that returns the number of even
numbers for a given array of numbers of n size.