Parameters passing methods
by hkesavaraju on Jan.28, 2010, under Advanced Data Structures
Parameter Passing Methods
These are the ways in which actual arguments are bound to formal parameters. There are 2 types of parameter passing methods used. They are:
[ad#adbrite_alone_ads]
- call by value or pass by value
- call by reference
- call by value: In this, the value of actual argument in calling function is just copied to formal argument of called function. If any changes happens on formal argument that doesn’t effect actual arguments.
The example is:
#include
#include
main()
{
clrscr();
int n=5;
fact(n);
cout <<”\n value of n after called function execution:”<
output is: factorial is:120
value of n after called function execution:5
In this program, value of n is the actual argument copied to k, which is changed in called function execution that doesn’t effect original value of actual argument n.
- call by reference: C++ provides call by reference by passing reference variables to calling function. In this, the actual arguments of calling function become aliases of formal arguments. When called function changes formal argument in its execution, the same will reflect in the actual arguments also.
The example is:
#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
int x=5,y=10;
swap(&x,&y);
cout<<”\n the actual x & y are:<<x<<”\t”<<y;
getch();
}
void swap(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
cout<<”the x & y after swapping are:”<<a<<”\t”<<b;
}
output is:
the x & y after swapping are:10 5
the actual x & y are: 10 5
In this program, the changes occur on formal arguments will same occur on actual arguments also.
Return by reference: A function can return a variable by reference. Example is:
int &max(int &x,int &y)
{
if x> y
return x;
else
return y;
}
When a function call max(a,b) is called, either reference of variable a or b is returned. This call also used as left hand operand in assignment statement like as shown below.
max(a,b)=-1;
it assigns -1 to a if a is larger than b,otherwise assigns -1 to b.