1. Functions in C++
■ Dividing a program into functions is one of the major principles of top-down,
structured programming
■ Reduces size of program
■ Example:
void show();
void main()
{ …….
show();
……..
}
void show()
{ ………
}
2. The Main function
■ Every C++ program must have a main function
■ A C++ program can have any number of functions but if it has only one function it
has to be the main function.
■ Execution of the program begins at the main function.
■ In C++, the main function returns a value of the type int to the operating system
3. Function prototyping
■ Declaration statement of a function
■ Syntax:
type function-name (argument list);
■ Names of arguments are optional in function prototyping but mandatory in function
definition
■ Examples of prototyping:
float volume(int x, int y, float z);
float volume(int , int , float);
4. Call By Value
void swapv(int,int);
void main( )
{ int a=10,b=20;
swapv(a,b);
cout<<a<<“ “<<b;
}
void swapv(int x,int y)
{ int t;
t=x;
x=y;
y=t;
cout<<“\n”<<x<<“ “<<y;
}
Output:
20 10
10 20
5. Call By Reference/Address
void swapr(int *,int *);
void main( )
{ int a=10,b=20;
swapr(&a, &b);
Page | 1
, cout<<“\n”<<a<<“ “<<b;
}
void swapr(int *x, int *y)
{ int t;
t=*x;
*x=*y;
*y=t;
cout<<*x<<“ “<<*y;
}
Output:
20 10
20 10
6. Return by Reference
■ A function can also return a reference
■ Example:
int & max(int &x, int &y)
{
if(x>y)
return x;
else
return y;
}
void main()
{
int a=5,b=10;
max(a,b)=-1; //is legal
cout<<a<<“ “<<b;
}
//Assigns -1 to a if it is larger otherwise -1 to b
7. Questions
Q.1) What are Functions In C++? Why are they used?
Q.2) Explain about the Main Function in a C++ program.
Q.3) What is Function Prototyping?
Q.4) Write a C++ program to implement Call by Reference.
Q.5) Write a C++ program to implement Call by Address.
Q.6) Write a C++ program to implement Call by Value.
Q.7) Write a C++ program to implement Return by Reference.
8. Inline Function
■ When a function is small and called many times, a substantial percentage of execution
time may be spent in overheads
■ Inline function is a function that is expanded in line when it is invoked
■ Inline function must be defined before calling
inline return_type function_name(arguments)
{ function_body
}
9. Default arguments
■ Assign a default value to the parameter, which does not have matching argument in
the function call. Default values are specified when the function is declared.
Eg : float amount(float principal, int period, float rate=0. 15);
Function call is Value=amount(5000,7);
Page | 2