GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

meaning of fun() = 30 in the given code

#include<iostream>
using namespace std;

int &fun()
{
    static int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

please explain the output of code...

asked Oct 3, 2016 by bambhole

1 Answer

For this to understand, you should know about reference in C++.

see this simple code explains about reference,

#include<iostream>

using namespace std;
int main()
{
    int a=5;
    int &b=a;
    cout<<a<<endl;     //output = 5
    cout<<b<<endl;     //output = 5
    b= b+3;
    cout<<a<<endl;     //output = 8
    cout<<b<<endl;     //output = 8
return 0;
}

It shows that, reference variable(b) has access to the original variable(a).

Likewise, the code that you have posted, fun() has a return type (int&), which means it returns the reference of the x . And most important, the statement , 

fun() = 30; assigns 30 to the returned reference by fun(). and hence , the output is 30.

I AM THANKFUL TO YOU TO HAVE ASKED SUCH A QUESTION,AS IT HELPED ME TO LEARN FEW THINGS TOO. Please do ask , if there is any confusion. 

Thank You. UP VOTE it if you are satisfied.

answered Oct 3, 2016 by Mazhar MIK
Reference variable
...