You are on page 1of 9

Functions in C++

C++ Functions:
In programming, function refers to a segment code to perform a specific
task. Depending on whether a function is predefined or created by programmer;
there are two types of function:
Library Function
Library functions are the built-in function in C++ programming.
Programmer can use library function by invoking function directly; they don't
need to write it themselves.
User-defined Function
C++ allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that
group of code is given a name(identifier).
When the function is invoked from any part of program, it all executes the
codes defined in the body of function.
Generally, C++ function has three parts:
 Function Prototype
 Function Definition
 Function Call

2.1 Function prototype:


In C++ we can’t use a function without telling the compiler about it. So
before calling a function, we must either declare or define a function.
If a user-defined function is defined after main() function, compiler will show
error. It is because compiler is unaware of user-defined function.
A function prototype is a declaration in C++ of a function i.e. its name,
parameters and return type before its actual defined.
Because the function prototype tells the compiler what to expect, the
compiler is better able to flag any functions that don't contain the expected
information.
The function prototype tells the compiler what to expect, what to give to
the function and what to expect from the function.
A function prototype is a declaration of function without its body and
terminated by a semicolon.
Syntax for function declaration-
return_type function_name (parameter list);
A prototype contains:
1) The return type of the data that the function will return.
2) The name of the function.
3) The number of arguments passed to the function.
Purpose of prototype:
1) A function prototype ensures that calls to a function are made with the
correct number and types of arguments.
2) A function prototype specifies the number of arguments.
3) It states the data type of each of the passed arguments.
4) It gives the order in which the arguments are passed to the function.
19
Functions in C++
Examples-
1) int add (int, int);
Here, the function name is add, its return type is integer and it takes
two input arguments, both of type int.
2) float add (float, int);
Here, the function name is add, its return type is float and it takes
two input arguments, first is float and second is integer.
3) void add (int, float);
Here, the function name is add, its return type is void and it takes
two input arguments, first is integer and second is int.
4) void add ();
Here, the function name is add, its return type is void and it takes
no input arguments.
Benefits of prototype:
1) Prototypes save debugging time.
2) Prototypes prevent problems that occur when you compile using
functions that were not declared.
3) When function overloading occurs, the prototypes distinguish which
function version to call.

Function Definition:
Function definition is a part where we define (code) the operation of a
function. It consists of the declarator followed by the function body.
Defining a function is a way of specifying how the operation is to be done
when the function is called.
The function should be defined outside of the main function.
Syntax for Function Definition-
return_type function_name (parameter list)
{
body of the function
}
Examples-
int add(int x, int y)
{ int res;
res = x + y;
return res;
}
Function Call:
To execute the codes of function body, the user-defined function needs to
be invoked(called).
Whenever a call statement is encountered, the control (program control) is
transferred to the function, the statements in the function-body are executed,
and then the control returns to the statement following the function call.
Syntax
function_name (argument_list);
Here, function_name is the name of the called function and argument_list
is the comma-separated list of expressions that constitute the arguments.
20
Functions in C++
/*04 Program for Swapping numbers using call by value in C++ */
#include<iostream.h>
#include<conio.h>
void swap(int , int );
int main()
{
int a, b;
clrscr();
cout<<"Enter any two numbers \n";
cin>> a >> b;
cout<<"\nBefore Swapping: \n";
cout<<"Value of First Number = "<<a << endl;
cout<<"Value of Second Number = "<<b << endl;
swap(a, b);
getch();
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
cout<<"\nAfter Swapping: \n";
cout<<"Value of First Number = " << x << endl;
cout<<"Value of Second Number = " << y << endl;
}
Output:

In C and C++ a user defined function cannot return more than one value
at once. Thus, when we use call by value, we need to print the values in called
function and not the calling function. To overcome this, we use call by reference
in C++, either through pointers or through reference variable.
The problem with pointers is that their reference may change during
execution of the program. Where as a reference variable in C++ always points to

21
an associated variable.
Functions in C++
2.2 Call by reference (using reference variable)
Reference variables
It provides an alias (alternative name) for a previously defined variable.
int i  declare a variable
int& r = i;  create reference variable
The call by reference method of passing arguments to a function 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 arguments inside the called
function affect the passed argument in the calling function.
/*05 Program for Swapping numbers by using reference variable in C++ */
#include<iostream.h>
#include<conio.h>
void swap(int& , int& );
int main()
{
int a, b;
clrscr();
cout<<"Enter any two numbers \n";
cin>> a >> b;
cout<<"\nBefore Swapping: \n";
cout<<"Value of First Number = " << a << endl;
cout<<"Value of Second Number = " << b << endl;
swap(a, b);
cout<<"\nAfter Swapping: \n";
cout<<"Value of First Number = " << a << endl;
cout<<"Value of Second Number = " << b << endl;
getch();
return 0;
}
void swap(int &x, int &y)
{ int temp;
temp = x;
x = y; //change in X makes changes in a
y = temp; //change in y makes changes in b
}
Output:

22
Functions in C++
2.3 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.
Values returned by reference must be variables. When a variable is
returned by reference, a reference to the variable is passed back to the caller.
Just like return by address, you should not return local variables by
reference because it will go out of scope.
Example
#include <iostream.h>
#include <conio.h>
int num; // Global variable
int& test(); // Function declaration
int main()
{ test() = 5;
cout << num;
return 0;
}
int& test()
{ return num;
}
Output : 5
In program above, the return type of function test() is int&. Hence, this
function returns a reference of the variable num.
The return statement is return num; Unlike return by value, this statement
doesn't return value of num, instead it returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in
test() = 5; This stores 5 to the variable num, which is displayed onto the screen.
Important Things to Remember When Returning by Reference.
1- Ordinary function returns value but this function doesn't. Hence, you
cannot return a constant from the function.
int& test()
{ return 2;
}
2- You cannot return a local variable from this function.
int& test()
{ int n = 2;
return n;
}
Example 2:

23
Functions in C++
2.4 Inline function
Inline function is one of the important features of C++.
Inline function is the function where, when a call is made to a function the
code of the called function gets placed in the calling function.
We can say that Inline works like a copy/paste controlled by the compiler.
Normally when we write a big code, we divide that code into smaller
functions. This helps us to better understand the logic of the program also it is
easier to maintain.
Now whenever a function gets called for execution, the CPU stores the
memory address of the instruction following the function call, copies the
arguments of the function on the stack and finally transfers control to the
specified function. This operation takes a lot of time.
This can become overhead if the execution time of function is less than the
switching time from the caller function to called function.
For functions that are large and/or perform complex tasks, the overhead of
the function call is usually insignificant 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.
C++ provides concept of inline functions to reduce the function call
overhead. Inline function is a function that is expanded inline when it is
called.
When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call. This substitution is
performed by the C++ compiler at compile time.
Inline function is suitable for small functions only. Incase of large
functions, it increases the execution time slowing down the performance.

Syntax:
inline return-type function-name(arguments)
{
// function code
}

To make any function as inline, place the keyword inline before the function
name and define the function
The keyword ‘inline’ only sends a request to the compiler not a command. To
accept the request or not to accept is completely upon the compiler.

Compiler may not perform inlining if-


1. If a function contains a loop. (for, while, do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement
doesn’t exist in function body.
5. If a function contains switch or goto statement.
24
Functions in C++
Example:
/*06 Program to find area of circle using inline function in C++ */
#include<iostream.h>
#include<conio.h>
inline float area (float r)
{
return (3.14 * r * r)
}
int main()
{
float radius;
clrscr();
cout << "Enter the value of radius of circle";
cin >> radius;
cout << "Area of circle = " << area(radius);
getch();
return 0;
}

/* Program to find minimum of Two numbers using inline function in C++ */


#include<iostream.h>
#include<conio.h>
inline float max (float r, float r)
{
return (x>y? x : y)
}
int main()
{
float num1, num2;
clrscr();
cout << "Enter Two Numbers";
cin >> num1 >> num2;
cout << "Among the two numbers " << max(num1 ,num2) << "is greater";
getch();
return 0;
}

/*Function to print factorial of first N natural numbers*/


inline void factorial(int x)
{ int i,f=1,p=1;
for(i=1;i<=x;i++)
{
f=f*i;
}
cout<<"Factorial of "<<x<<" is "<<f<<endl;
}
The computation of factorial in the above function involves repeated
multiplication and loop which makes the function large. So, the compiler will
ignore the request to make it inline and treats it as normal function.
25
Functions in C++
2.5 Default arguments
In C++ programming, you can provide default values for function argument.
A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the caller of the function doesn’t provide
a value for the argument with a default value.
The idea behind default argument is simple. If a function is called by
passing argument/s, those arguments are used by the function.
But if the user does not supply an explicit argument for a parameter with
a default argument, the default value will be used.
As the user can choose whether to supply a specific argument value, or use
the default, a parameter with a default value provided is often called an optional
parameter.
The default arguments get assigned during compilation of program. When
a program is compiled the compiler looks at the prototype of the function and
sees how many arguments a function uses and take note of argument declared
with default value.
Synatx
In function header while declaring the function
Return_Type Function_Name ( Data_Type Variable_Name Default_Value);
Example :
int sum (int x, int y, int z=0, int w=0);
Note: Only the trailing arguments can have default values and therefore we must
add default values form right-to-left.
This means that in our example ‘z’ can a default value only if ‘w’ has default
value. Similarly, ‘y’ can have a default value if both ‘w’ and ‘z’ have a default value.
Exercise:
Function header Valid/Invalid
int Add(int x, int y, int z=30);
int Add(int x, int y=20, int z=30);
int Add(int x, int y=20, int z);
int Add(int x=10, int y, int z=30);
int Add(int x=10, int y=20, int z=30);
#include<iostream.h>
void demo (int a = 0, int b=0); //Default value of a & b is 0
void main()
{
int c = 100, d = 200;
demo ();
demo (c);
demo (d);
demo (c,d);
demo (d,c);
}
void demo (int a, int b)
{ cout << "a = " << a <<"\t" << "b = " << b << "\n ";
}
26
Functions in C++
/*07 Program to simple interest using default arguments */

#include<iostream.h>
#include<conio.h>
float interest (float P, float N, float r = 8.25);
int main()
{
float P, N;
clrscr();
cout <<"Enter principal amount: ";
cin >> P;
cout <<"Enter duration in years: ";
cin >> N;
cout << "your intrest amount is : " << interest(P,N);
getch();
return 0;
}
float interest (float P, float N, float r)
{
return (P*N*r)/100;
}
Output:

2.6 Const arguments


In C++, you can choose whether or not you want the function to be able to
change the value of argument you pass.
If an argument to a function is declared as const the function will not able
to change its value. The argument with constant value should be initialized during
the function declaration.
Example :
#include<iostream.h>
#include<conio.h>
void demo (const int x);
void main()
{
clrscr();
demo (10);
}
void demo (const int x)
{
for (int i = 0; i < 5; i++)
{ x = x + i * 10;  Error: you cannot assignee value to a constant.
cout << "\t" << x; }
}
27

You might also like