Here is a simple C program containing a function that alters the value of its argument.
#include stdio.h
void modify (int a) /*function prototype*/
main()
{
int a=2;
printf("\na=%d (from main, before calling the function)", a);
modify(a);
printf("\na=%d (from main, after calling the function)",a );
}
void modify(int a)
{
a*=3;
printf("\na=%d (from the function, after being modified)",a );
return;
}
The original value of a (i.e. a=2) is displayed when the main begins execution.This value is then passed to the function modify,where it is multiplied by 3 and the new value is valued.Note that it is the altered value of the formal argument that is displayed within the function.Finally,the value of a within main (i.e. the actual argument) is again displayed,after control is transferred back to main from modify.
When the program is executed the folloing output is generated.
a=2 (from main, before calling the function)
a=6 (from the function, after being modified)
a=2 (from main, after calling the function)
These results show that a is not altered within the main,even though the corresponding value of a is changed within modify.
Passing an argument by value has advantages and disadvantages.On the plus side,it allows a single valued actual argument to be written as an expression rather than being restricted to a single variable.Moreover, if the
actual argument is expressed simply as a single variable,it protects the value of this variable from alteration within the function.On the other hand, it does not allow information to be transferred back to the calling portion of program via arguments.Thus, passing by value is restricted to a one-way transfer of information.
No comments:
Post a Comment