Pass by Reference with Pointers
It is also possible to pass the variable address from the calling function and use them as a pointer inside the called function. This allows a bit more explicitly in the change of variable values in the function.
Below is the C++ program to implement pass-by-reference with pointers:
C++
// C++ program to implement // pass-by-reference with // pointers #include <iostream> using namespace std; void f( int *x) { *x = *x - 1; } // Driver code int main() { int a = 5; cout << a << endl; f(&a); cout << a << endl; } |
5 4
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 turned out to be 1 less than the original value.
C++ Functions – Pass By Reference
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. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory location of the passed variable and parameter is the same. Therefore, any change to the parameter also reflects in the variable inside its parent function. This article focuses on discussing how to pass variables by reference in C++.
Contact Us