Hi All,
Pleas tell me why the following program is giving 35 as output??
if fun() returns int type then it is compilation error. why?

#include<iostream>
using namespace std;

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

When I ran your code I got the expected value of 30. As such I cannot explain why yours is outputting 35, but I can explain why fun had to return an integer reference instead of an integer. Basically when a function returns an int (a normal one) then it is assumed to be an r-value. Basically this means that it will act identically to what would happen if you swapped out the function with its return value. Returning the reference changes the return value into an actual variable rather than a value. Here is equivalent code for both situations:

int fun()
{
    static int x=10;
    return x;
}
fun()=30;//this will become:
10=30;//which is obviously an error! 

//however:

int &fun()
{
    static int x=10;
    return x;
}
fun()=30;//this will effectively become:
fun_x=30;//note that fun_x is actually the X inside fun.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.