Pass by Value and Pass by Reference
We have seen as to how to pass values to a function by making use of arguments. First let me make one concept clear. What is a parameter and what is an argument? Parameter is the variable that you declare within the function. Argument is the variable that you pass to a function.
Pass By Value
Example
:
void check ( int x )
{....................
}
int main ( )
{
...........................
int b = 10;
check (b);
......................
}
In this function, x is a parameter and b ( which is the value to be passed ) is the argument. In this case the value of b (i.e. the argument) is copied in x (i.e. the parameter). Hence the parameter is actually a copy of the argument. The function will operate only on the copy and not on the original. This method is known as PASS BY VALUE. So far we have dealt only with pass by value.
//
Pass by value illustration
int square (int x)
{
return x*x;
}
int main ( )
{
int a = 10;
int answer;
answer = square(a);
cout<<"Answer is "<<answer;
// answer is 100
cout<<" Value of a is "<<a;
// a will be 10
return 0;
}
You can see that the value of a is unchanged. The
function square works only on the parameter (i.e.
on x ).
Next section we shall take a look at : Pass By Reference
Or you can go to Contents page 2.