Discuss the different parameter passing techniques

Estudies4you

Parameter Passing, Default Arguments

Q39. Discuss the different parameter passing techniques.
Answer:

Parameter Passing Techniques
There are two ways of passing parameters to a function,
1. Call-by-value
2. Call-by-reference

1. Call-by-value Mechanism
In this method, values of the actual arguments in the ‘calling function’ are copied into the corresponding parameters in the ‘called function’. Hence, the modifications done to the arguments in the ‘called’ function will not be reflected back to the actual arguments. x ‘

Example
#include<iostream.h>
#include<conio.h>
void add(int, int);
main( )
{
it x=10, y = 20;
add(x, y);
cout<<“The values of x and y in the calling function are”;
cout<<x<<y;
}
void add(int a, int b)
a=a+b;
b=b+2;
cout<<“a="<<a<<“b="<<b;
}
In the above program, the values of the actual parameters i.e., x and y are passed to the function “add(int a, int b)”; and a stack is maintained in the memory for storing the parameters i.e., when a function call is executed, the actual values of the parameters are placed on the stack. These values can be used and modified by the ‘called’ function without making any changes to the original variables. 
Figure (1): Call-by-value Mechanism

2. Call-by-reference Mechanism
In this method, the addresses of the actual arguments are copied to the corresponding parameters in the ‘called’ function. Hence, any modifications done to the formal parameters in the ‘called function’ causes the actual parameters to change.
Example
#include <iostream.h>
#include <conio.h>
void add(int*, int*);
main()
{
int x = 10, y = 20;
add(&x, &y); ¢
cout<<“The values of x and y in the calling function \n”;
cout<<“x="<<x<<“y="<<y;
}
void add(int *a, int *b)
{
*a=*a + *b;
*b=*b +2;
cout<<“a="<<*a<<"b="<*b;
}
In the above program, the addresses of ‘x’ and ‘y' are passed to ‘a’ and ‘b’. Hence, they refer to the same address location as referenced by ‘x’ and ‘y’. The addresses of the arguments are placed in the stack, hence any modifications done in the ‘called’ function will apply to the ‘calling’ function.
Figure (2): Call-by-reference Mechanism
To Top