4. Function
4. Function
1
// calling the function
displayNum(num1, num2);
return 0;
}
Output
The int number is 5
The double number is 5.5
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.
Return Statement
It's also possible to return a value from a function. For this, we need to specify the return Type of the
function during function declaration.
Then, the return statement can be used to return a value from a function.
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>
using namespace std;
int add(int a, int b)
{
return (a + b);
}
int main()
{
int x, y, sum;
cout<<”enter the value of a and b:”
cin>>a>>b;
// calling the function and storing
// the returned value in sum
sum = add(x, y);
cout << "a+b= " << sum << endl;
return 0;
}
Output
Enter the value of a and b:10
20
a+b = 30
Note: in the above example a and b are known as formal parameters and x and y are known as
actual parameters.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we want to
define a function after the function call, we need to use the function prototype.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
Example 4: C++ Function Prototype
#include <iostream>
using namespace std;
// function prototype
int add(int, int);
int main()
{
2
int sum;
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
// function definition
int add(int a, int b)
{
return (a + b);
}
Output
100 + 78 = 178
3
char *ch // pointer to character
Example1:
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Output
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Reference:
A reference variable is an alias, that is, another name for an already existing variable. Once a
reference is initialized with a variable, either the variable name or the reference name may be used
to refer to the variable.
Example:
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Example1:
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Output:
Value of i : 5
Value of i reference : 5
4
Value of d : 11.7
Value of d reference : 11.7
5
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
// function definition to swap the values.
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
3 Call by Reference
This method 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 parameter affect the argument.
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
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;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Before swap, value of a :100
Before swap, value of b :200
6
After swap, value of a :200
After swap, value of b :100
Return by reference:
In C++ Programming, not only can you pass values by reference to a function but you can also return
a value by reference.
Example:
#include <iostream>
using namespace std;
int& max(int& x, int& y);
int main()
{
int a=10,b=20;
cout<< "Enter the value of a and b:";
cin>>a>>b;
max(a,b) = -1;
cout <<"a="<<a<<"\nb="<<b;
return 0;
}
int& max(int& x,int& y)
{
if(x>y)
return x;
else
return y;
}
Output
Enter the value of a and b:10
20
a=10
b=-1
Note: Ordinary function returns value but this function doesn't. Hence, you cannot return a constant
from the function.
int& test()
{
return 2;
}
You cannot return a local variable from this function.
int& test()
{
int n = 2;
return n;
}
Recursion:
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call and the other doesn't.
7
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
8
Default Arguments (Parameters):
we can provide default values for function parameters.
If a function with default arguments is called without passing arguments, then the default
parameters are used.
However, if arguments are passed while calling the function, the default arguments are ignored.
Example:
#include <iostream>
using namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
void display(char c, int count) {
for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
Note:
• Once we provide a default value for a parameter, all subsequent parameters must also have
default values.
• If we are defining the default arguments in the function definition instead of the function
prototype, then the function must be defined before the function call.
Function Overloading:
Two functions can have the same name if the number and/or type of arguments passed is different.
Example:
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Example1:
#include <iostream>
9
using namespace std;
Inline Function:
To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An
inline function is a function that is expanded inline when it is invoked. That is the compiler replaces
the function call with the corresponding function code.
The inline functions are defined as follows: -
inline function-header
{
function body;
}
Example:
inline double cube (double a)
{
return(a*a*a);
}
The above inline function can be invoked by statements like c=cube(3.0);
d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the compiler. The
compiler may ignore this request if the function definition is too long or too complicated and
compile the function as a normal function.
10
Some of the situations where inline expansion may not work are:
1. For functions returning values if a loop, a switch or a go to exists.
2. for functions not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive.
Example:
#include<iostream.h> #include<stdio.h>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p.double q)
{
return(p/q);
}
main( )
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
}
output
121.227898
1.257128
Constant Argument:
In C++,an argument to a function can be declared as unit as const as shown below.
int strlen(const char *p);
int length(const string &s);
The qualifier const tells the compiler that the function should not modify the argument. The
compiler will generate an error when this condition is violated. This type of declaration is significant
only when we pass arguments by reference or pointers.
11