C++ Tutorial C++ Advanced C++ References

C++ Functions - Pass by Reference



When the argument or parameter of a function is passed by reference, then the function takes the parameter as reference and any changes made to the parameter inside the function will change the parameter itself also. By default, C++ uses pass by value method. To pass an argument by reference ampersand sign (&) is used just before variable name. To pass by reference means that the code within a function will change the parameter used to pass in the function.

Example:

In the example below, the function called Square is created which returns square of the passed argument. The function modify the parameter as square of itself before returning it. In the main() function, when the passed argument is printed after calling the function Square, the value of the parameter changes because it was passed by reference.

#include <iostream>
using namespace std;
int Square(int &x); 

int main (){
    int x = 5;
    cout<<"Initial value of x: "<<x<<"\n";
    Square(x);
    cout<<"Value of x, after passed by reference: "<<x<<"\n";
    return 0;
}

int Square(int &x){
    x = x*x;
    return x; 
}

The output of the above code will be:

Initial value of x: 5
Value of x, after passed by reference: 25

❮ C++ - Functions