If parameters are passed by value what will be printed when
If parameters are passed by value, what will be printed when the following program segment is executed?
X = 9
Modify(X)
print(X)
What would be printed if the parameters are passed by reference?
Solution
a) pass by value:-
#include <stdio.h>
int modify(int z);
int main() {
int x=9;
modify(x);
printf(\"%d\",x);
return 0;
}
int modify(int z)
{
int y=3;
z=z+y;
return(z);
}
output:- 9
The value of x will not be modified in the resulting main function because in pass by value the value of formal parameter does not reflect the value of actual parameter.
If we will print the value of z in modify() function then the result will be 12.
b) Pass By Reference:-
#include <stdio.h>
void modify(int *z);
void main() {
int x=9;
modify(&x);
printf(\"%d\",x);
}
void modify(int *z)
{
int y=3;
*z=*z+y;
}
Output:- 12
The value of x will be modified in the resulting main function because in pass by reference the value of formal parameter reflect the value of actual parameter.
