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++.


Related Tutorials

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.