Home » C++ programming language

Example of Function returning reference in C++



C++ - Function returning reference: Here, we will learn with a C++ program, how to return a reference from function?

As we know that we can take only variable on the left side in C++ statements, we can also use a function on the left side, if a function is returning a reference to the variable. The variable whose reference is being returned may only be:

  1. Global variable
  2. Static variable

Using this type of function, we can assign variable. We can understand this situation with the help of the program.

Consider the program:

using namespace std;
#include <iostream>

int X; //Global variable

//prototype of funToSetX()
int & funToSetX();

int main()
{
    X = 100;
    
    int Y;
    
    Y = funToSetX();
    cout<<"1.Value of X is : "<< Y<<endl;
    
    funToSetX() = 200;
    
    Y = funToSetX();
    cout<<"2.Value of X is : "<< Y<<endl;
        
    return 0;    
}

//Definition of funToSetX()
int & funToSetX()
{
    return X;    
}

Output

1.Value of X is : 100
2.Value of X is : 200

In this program, we are using X as a global variable and using function funToSetX(), we are returning a reference to global variable X. We assign 100 to X in starting of main() function, then get value of from funToSetX() to Y. So, here we are using funToSetX() function on left and right both side in C++ statement. Normally we cannot do this with normal functions in C++.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.