Functions in C++
Functions in C++
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
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.
#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: