Function in C++
Function in C++
i. A function is a group or sequence or list of statements that together perform a particular task.
ii. Every C++ program has at least one function, which is main () function.
iii. Function divides a large program into smaller program to perform a particular task.
iv. The main advantage of function is to decrease the complexity of program and remove the
repetition of code.
Types of Functions
There are two types of functions in C++ programming:
1. Library function
2. User defined function
1. Library function come along with compiler and are presented in the C++ header file such as
ceil(),pow(),strcpy(),strcmp(), scanf(), printf(), sqrt() etc.
2. User- defined functions are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the code.
For better understanding of arguments and return type in functions, user-defined functions can be
categorized into 4 types:
1
Function with argument but no return value
void add(int,int);
Eg:
void show(); //function declaration or void show()
{
cout<<”Welcome”;
}
int main()
{
return 0;
//function body
Consider a situation in which you have to find the maximum of two numbers. This problem is solved by
making user-defined function in 4 different ways.
2
Example: Write a function in C++ to find the maximum of two numbers.
#include <iostream>
using namespace std;
int a,b,max;
cout<<"Enter the two numbers:";
cin>>a>>b;
cout<<"Maximum number:"<<max;
return 0;
}
Function Prototype
A function prototype deceleration consists of the function name, function return type and argument list.
When the programmer defines the function, the definition of the function must be like its prototype
deceleration. If the programmer makes a mistake, the compiler flags an error message. The function
prototype deceleration statement is always terminated with semicolon.
Example:
void max();
int max();
void max(int,int);
3
int max(int,int)
#include <iostream>
using namespace std;
int a,b,max;
cout<<"Enter the two numbers:";
cin>>a>>b;
cout<<"Maximum number:"<<max;
return 0;
}
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are three ways/methods that arguments can be passed to a function –
4
1. Call by value-
In call by value, value of actual argument is passes to the formal argument and operation
is done on the formal arguments. Any change in the formal argument does not affect the
actual argument because formal arguments are photocopy of the actual arguments.
Hence, when function is called by call by value method, it does not affect the actual
contents of the actual arguments.
Changes made in the formal argument are local to the block of called function. Once
control returns back to the calling function the change made vanish.
By default, C++ uses call by value to pass arguments.
Example:
int main () {
// local variable declaration:
int a = 100;
int b = 200;
5
2. Call by address/pointer(pass by address)
In call by address, instead of passing values, addresses are passed.
Function operates on address rather than values.
Here the formal arguments are pointers to the actual arguments.
Hence changes made in the arguments are permanent.
Example:
int main () {
// local variable declaration:
int a = 100;
int b = 200;
swap(&a, &b);
return 0;
6
}
3. Call by reference
In C++ reference type/variable, declared with “&” operator are nearly identical but not
exactly same to pointer type.
A reference variable provides an alias for a previously defined variable i.e the same
variable’s value can be used by two different names; the original name and alias name.
A reference variable must be initialized at the time of declaration.
A reference variable is an alias i.e another name for an already existing
variable
Eg:
int k = 0;
int &kk=k; //kk is an alias for k
kk = 10; //any operation on kk will give the same result as operations on k.
Call by reference copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means that
changes made to the formal parameter affect the actual argument.
7
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
return 0;
}
Q: Write a member function in C++ which accepts one number as a parameter/argument and
calculate the factorial of given number.
8
Q: Write a member function in C++ which accepts one number as a parameter/argument and Check
Whether a Number is Prime or Not.
Q: Write a member function in C++ which accepts one number as a parameter/argument and
calculate the factorial of given number and return the calculated factorial to the calling function.
Q: Write a function in C++ which accepts one number as a parameter/argument and return the
reverse number of the given number to the calling function.
#include<iostream>
using namespace std;
void add(int x,int y,int &z)
{
z=x+y;
}
main()
{
int a,b,s=0;
system("CLS");
cout<<"Enter the two numbers:";
cin>>a>>b;
add(a,b,s);
cout<<endl<<"sum=\t"<<s;
return 0;
#include<iostream>
using namespace std;
int &add(int x,int y)
{
int z=x+y;
int &r=z;
return r;
}
main()
{
int a,b,s=0;
system("CLS");
9
cout<<"Enter the two numbers:";
cin>>a>>b;
s=add(a,b);
cout<<endl<<"sum=\t"<<s;
return 0;
If you want to pass array as a parameter to the function than function deceleration specify the
data type of array and empty square bracket([]) and when you call the function than just pass
the name of the array.
Let's see the simple example to get the maximum number of an array using a function.
#include <iostream>
using namespace std;
void find_max(int no,int x[])
{
int i,max=0;
for(i=0;i<no;i++)
{
if(x[i]>max)
max=x[i];
}
cout<<"Max:\t"<<max;
}
main()
{
int i,no,a[10],max;
find_max(no, a);
return 0;
}
Q: create a function in C++ that takes/accept two parameters/argument: an integer array and
array size; return the smallest value to calling function.
10
Advantage of functions in C++
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same code again
and again.
2) Code optimization
Example:
Suppose, you have to check 3 numbers (112, 553 and 21) whether it is prime number or not. Without
using function, you need to write the prime number logic 3 times. So, there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several times.
11