Unit-4.2, Notes
Unit-4.2, Notes
Simple functions
C++ User-de ned Function
C++ allows the programmer to de ne their own function.
A user-de ned function groups code to perform a speci c task and that
group of code is given a name (identi er).
When the function is invoked from any part of the program, it all executes the
codes de ned in the body of the function.
Example:
// function declaration
void greet() {
cout << "Hello World";
}
Function Call
int main() {
// calling a function
greet();
It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,
fi
fi
fi
fi
fi
fi
fi
fi
fi
int add (int a, int b) {
return (a + b);
}
The code return (a + b); returns the sum of the two parameters as the
function value.
The return statement denotes that the function has ended. Any code after
return inside the function is not executed.
Function Prototype
In C++, the code of function declaration should be before the function call.
However, if we want to de ne a function after the function call, we need to
use the function prototype. This provides the compiler with information about
the function name and its parameters. That's why we can use the code to
call a function before the function has been de ned.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header le
in which these library functions are de ned.
In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location. If you change the value of
function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main().
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is re ected inside as well as outside the function.
EXAMPLE:
#include<iostream>
using namespace std;
fl
fi
fi
fi
fi
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output:
When the program executes the function call instruction the CPU stores
the memory address of the instruction following the function call, copies
the arguments of the function on the stack and nally transfers control to
the speci ed function.
The CPU then executes the function code, stores the function return value
in a prede ned memory location/register and returns control to the calling
function.
This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of
the function call is usually insigni cant compared to the amount of time the
function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code.
This overhead occurs for small functions because execution time of small
function is less than the switching time.
Compiler can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
3) If a function is recursive.
fi
fi
fi
ffi
fi
fi
4) If a function return type is other than void, and the return statement
doesn’t exist in function body.
4) When you inline a function, you may enable compiler to perform context
speci c optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the ows of calling context and the called context.
2) If you use too many inline functions then the size of the binary
executable le will be large, because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that
of primary memory.
Example:
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //
2 Through inline function, the class’s Whereas macro can’t access the
data members can be accessed. class’s data members.
3 In the case of inline function, the Whereas in the case of macros, the
program can be easily debugged. program can’t be easily debugged.
4 In the case of inline, the arguments Whereas in the case of macro, the
are evaluated only once. arguments are evaluated every time
whenever macro is used in the
program.
ff
fi
fi
fi
fi
5 In C++, inline may be de ned either Whereas the macro is all the time
inside the class or outside the class. de ned at the beginning of the
program.
6 In C++, inside the class, the short While the macro is speci cally
length functions are automatically de ned.
made the inline functions.
7 Inline is not as widely used as macros. While the macro is widely used.
8 Inline is not used in competitive While the macro is very much used
programming. in competitive programming.
FUNCTION OVERLOADING
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is oat " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
fi
fi
fl
fi
fi
ff
ff
ff
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is oat 10.1
Here is char* ten
3. If no match found:
->C++ tries to nd a match through the standard conversion.
ELSE ERROR
// Driver Code
int main()
fl
fi
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80
OUTPUT: ERROR
fl
fl
fi
Default arguments are di erent from constant arguments as constant
arguments can’t be changed whereas default arguments can be
overwritten if required.
Default arguments are overwritten when calling function provides values for
them. For example, calling of function sum(10, 15, 25, 30) overwrites the
value of z and w to 25 and 30 respectively.
Once the default value is used for an argument in the function de nition, all
subsequent arguments to it must have a default value. It can also be stated
as default arguments are assigned from right to left. For example, the
following function de nition is invalid as the subsequent argument of
default variable z is not default.
fi
ff
fi
FRIEND FUNCTIONS
Friend functions of the class are granted permission to access private and
protected members of the class in C++. They are de ned globally outside
the class scope. Friend functions are not member functions of the class.
The friend function is declared using the friend keyword inside the body of
the class.
We declare friend function inside the body of a class, whose private and
protective data needs to be accessed, starting with the keyword friend to
access the data. We use them when we need to operate between two
di erent classes at the same time.
• It cannot access the member names directly and has to use dot
membership operator and use an object name with the member name.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box (): length (0) {}
friend int printLength (Box); //friend function
};
int printLength (Box b)
{
b. length +=10;
return b. length;
}
int main ()
{
Box b;
cout <<” Length of box:” <<printLength
(b)<<endl;
return 0;
}
Output:
Length of box:10
#include<iostream>
using namespace std;
class B; //forward declaration.
class A
{
int x;
public:
void setdata (int i)
{
x=i;
}
friend void max (A, B); //friend function.
} ;
class B
{
int y;
public:
void setdata (int i)
{
y=i;
}
friend void max (A, B);
};
void max (A a, B b)
{
if (a.x >= b.y)
std:: cout<< a.x << std::endl;
else
std::cout<< b.y << std::endl;
}
int main ()
{
A a;
B b;
a. setdata (10);
b. setdata (20);
max (a, b);
return 0;
}
Output:
20