If you like my posts please leave a comment.

Tuesday, October 9, 2012

Calling a Function by Value (Passing by Val):



A function can be called or invoked in two ways: call by value (passing by value of the variable(s)) and call by reference (passing by address of variable(s)). In call by value method, values of the actual parameter are copied into the corresponding formal parameters. In other words we can say that, in this method of function calling a function works with the copy of its own argument values. Let’s try to understand this concept more with the help of a simple diagram. 



In the above example, the value 15 of variable val is passed form the main() function to the function definition of modify() and is assigned to variable X, which is the formal argument of the function modify(). So, the value of actual argument of the function is copied to the formal argument of the same function definition. Now, the question is why I have used here the term ‘copied’? To find the answer of this question see the sample code. Please note here, when cout<<x line is executed in the function definition it will print the output as 17. On the other hand when cout<<val is executed in the main() it produces the output as 15. This proves that the value 15 is taken from a particular memory location and then copied to another memory location and that is why any operation with the value in the new location will not put effect on the value in the previous location. 

Say, the variable val is in memory location 0x0012ff88 and it is storing value 15. Now the value is copied to X, which is another variable in the new memory location say 0x0012ff84. Now any operation done with 15 at location 0x0012ff84 will not put effect on the value 15 stored in the location 0x0012ff88.
            In this case one thing I want to make you clear that, same variable name can also be used for actual argument and formal argument. Even though they hold the same name but they are not the same variables because they are created in different memory location. In C++ Arrays are not passed by value they are always passed by reference.
 
N
ote: When argument (a local variable) is passed by value, a copy of the variable’s value is assigned to the receiving function’s parameter. If more than one variable is passed by value, a copy of each variable’s value is assigned to the receiving function’s parameter.

No comments:

Post a Comment