Call-By-Reference in Functions
The call by reference uses a different mechanism. In place of passing value to the function, which is called, a reference to the original variable is passed. A reference is an alias for the predefined variable. That is, the value of that variable can be accessed by using any of the two: the original or the reference variable name.
When a function is called by reference, then the formal parameters become reference to the actual parameters in the calling function. This means that, in call by reference method, the called function does not create its own copy of the original values, rather, it refers to the original values only by different names. This called function works with the original data and any change in the value is reflected back to the data.
To write a function, which returns multiple output, we have to pass parameters by reference.
We use & to denote a parameter that is passed by reference:
Example:
- The address (reference) of the actual variable is passed to the function, instead of its value.
- If the function changes the parameter's value, the change is reflected back in the actual variables in the called function, since they share the same memory location.
In the above program, the function change() refers to the original value of orig, which is 10, by its reference a. The same memory location is referred to by orig in main() and by a in change(). Hence the change in a , by assigning value20, is reflected in orig also.
Pass-by-value Vs Pass-by-reference
This program uses two functions, one using pass-by-value method and the other using pass-by-reference method. This shows how the value of number does not change in the main function, when it is evaluated using pass-by-value method and on the other hand it changes when implemented using pass-by-reference method.
Comments - No Responses to “Call-By-Reference in Functions”
Sorry but comments are closed at this time.