I was going through some sample code related to using a function in left side of the assignment operation as lvalue. I'm having few doubts regarding this The first code is-
#include<iostream>
using namespace std;
static int x = 10;
int &foo()
{
cout << "inside func-- " << x << endl;;
return x;
}
int main()
{
foo() = 30;
cout << "printing from main-- " << foo() << endl;
return 0;
}
The output I get is-
inside func--10
inside func--30
printing from main--30
Why is the second statement printed before the 3rd statement. The 2nd line of the output should have been "printing from main-- inside func--30" and the third line should have been "30".
Also the second code is-
#include<iostream>
using namespace std;
int foo(int &x)
{
return x;
}
int main()
{
cout << foo(10);
return 0;
}
the above code fails to compile but when I try changing the type of reference from int to const int, the above code compiles. Why is it so ?