0

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;
}
2
Contributors
1
Reply
13
Views
4 Years
Discussion Span
Last Post by Labdabeta
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.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.