Call By Value and Call By Reference C Plus Plus [C++ Tutorials – 6]

11-09-2016
Call By Value and Call By Reference C Plus Plus
Call By Value and Call By Reference C Plus Plus

Call By Value and Call By Reference C Plus Plus

Call By Value and Call By Reference C Plus Plus

There are two ways to invoke a function in C++; Call by value and Call by reference.

Call by value:

In call by value method of function calling, the function copies the values of actual parameters into the formal parameters. ie. the function creates it’s own copy of argument values and then uses them. The changes done to the values of the formal parameters are not reflected back into the calling program.

The following program is an example of the Call by value.

PROGRAM TO INTERCHANGE THE VALUES OF TWO VARIABLES
--------------------------------------------------

#include <iostream.h>
#include <conio.h>
void swapping (int, int);

void main( )
{
clracr ( );
int a, b;
 cout<<"Enter the value of a: ";
 cin>>a;
 cout<<"Enter the value of b: ";
 cin>>b;
swapping (a, b);
 cout<<"The numbers are a = "<<a<<" and b = "<<b;
}

void swapping (int x, int y)
{
int t;
 t = x;
 x = y;
 y = t;
}

In the above example program, the values of a and b will not be changed in the actual parameter by the calling of function.

Call By Reference

When a function is called by reference the formal parameters become the references to the actual parameters in the calling function. ie. the called function does not create its own copy of original values. It refers to the original values only by alias names (references). Thus the called function works with the original data and any change in the values gets reflected the data.

The below program is the example for Call By Reference.

PROGRAM TO INTERCHANGE THE VALUES OF TWO VARIABLES
--------------------------------------------------
#include <iostream.h>
#include <conio.h>
void swap (int&, int&);
void main( )
{
clrscr( );
int a = 10, b = 5;
swap (a, b);
cout<<"a = "<<a<<" b= "<<b;
}

void swap(int &x; int &y)
{
int t;
t = x;
x = y;
y = t;
}

In the above example program, the values of actual parameters will be changed.

Tagged in: