Sections


Main-Menu

header image

Parameter passing


Parameter passing

In parameter passing, parameters are transferred between functions when one function calls another. In C++ two types of parameter passing are there, pass by value and pass by reference.

Pass by value
The method by which the parameter is passed to a function is determined by the function definition. The arguments appearing in the function definition are the formal parameters and if this formal parameter is not reference then the parameter passing is known to be pass by value.
e.g.
void temp (int x)
{
x=1;
cout<<<”\n”;
}
void main ()
{
int y = 5;
temp (y);
cout<<<”\n”;
}
The above program works as; the effect of the formal parameter definition is to create a local variable of the specified type in the given function. E.g., the function temp has a local variable of type int called x. When the function is called, the values (r-values) of the actual parameters are used to initialize the formal parameters before the body of the function is executed. Since the formal parameters give rise to local variables, if a new value is assigned to a formal parameter, that value has no effect on the actual parameters.

Therefore, the output obtained produced by the function main defined in program is,
1
5

Pass by Reference
If a function is called that has a formal parameter as reference, the effect of the call is to associate the reference with the corresponding actual parameter. i.e., the reference becomes an alternative name for the actual parameter. This simply means that the actual parameter passed by reference must be variable.
e.g.
void temp (int &x)
{
x=1;
cout<<<”\n”;
}
void main ()
{
int y = 5;
temp (y);
cout<<<”\n”;
}
A reference formal parameter can be used in the called function everywhere that a variable can be used. In particular, if the reference formal parameter is used where a r-value is required, it is the r-value of actual parameter that is obtained. Similarly, if the reference parameter is used where an l-value is required, it is the l-value of actual parameter that is obtained.

Therefore, the output obtained produced by the function One defined in program is:
1
1


Related Articles :



Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Shaadi.com Matrimony - Register for FREE