C++ Function Call By Pointer
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference.
Before swap:1 2 After swap:2 1 Sum:3
Another lesser-known method is Call by Pointer. Passing by a pointer allows a function to modify a variable without creating a copy.
Call by Pointer
When a call-by-pointer method is used for passing arguments to a function, the address of the variable is passed as an argument to the function. The function stores this address of variables in a pointer variable. Hence, the variable inside the function is an alias for the passed variable since both contain the same address. Therefore, any operations performed on the variable inside the function will also be reflected in the calling function.
- This ability to reflect changes could return more than one value by a function.
- Also, a void function could technically return value/s using this method.
The & (address of) operator in the actual parameters denotes values passed by pass-by-pointer in a function.
Function Call by Pointer
Passing the variable address from the calling function and using them as a pointer inside the function is called the call-by-pointer. This method allows clearer visibility of functions in which the value of the passed variables may change. i.e., In pass-by-reference, there is no indication in the function call that could be used to determine that the value of the passed variables may change in it (as the call is identical to call by value). But in call-by-pointer, the address operator & is used in the function call, providing a bit more intel about the nature of the function.
Explanation: Firstly a function is defined with the return datatype void and takes in value as pointers (as denoted by the * asterisk sign in the formal parameters). The function decrements the value of its formal parameter by 1. After which, inside the main function, an integer variable named ‘a’ is initialized with the value 5. Then this value is displayed. The function is called, and the address of the variable is passed as an argument.
Inside the function, the pointer variable’s value is decremented by 1. Upon returning from the function, the variable’s value is again displayed, which turns out to be 1 less than the original value.
Please Login to comment...