1

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 ?

uncletall
  • 6,609
  • 1
  • 27
  • 52
Backspace
  • 292
  • 1
  • 4
  • 17

1 Answers1

0

"Why is the second statement printed before the 3rd statement."

operator<< write its data to buffer. When that buffer is full ( Or someone flushes the buffer OR something else) then only it goes on to write data on screen. This mismatch with expected order is a consequence of that only as if you use

cout << "printing from main-- "<<endl;
cout << foo()<<endl;

The order would be same you specified as endl flushes the buffer.

The above code fails to compile but when I try changing the type of reference from int to const int?

You cannot bind temporary foo(10) to non-const reference. You have to use const reference there.

ravi
  • 10,994
  • 1
  • 18
  • 36
  • thanks for the easy explanation for the first part. Can you please elaborate on the second part of your answer. according to C++ standards, we need to pass const reference so that the function cannot change the value of the variable being passed . But here I'm passing an int value 10, which is not a variable, so why should the compiler worry about getting its value changed. ?. – Backspace Dec 12 '14 at 07:16
  • So, let's assume compiler allows you to bind '10' to non-const reference 'x'. And then in that function you try to modify 'x'. Would it make sense to modify 'x' as it's referring to '10'. So, compiler does a simple thing, it prohibits you from binding temporaries to non-const references... – ravi Dec 12 '14 at 07:20
  • Thanks, for clearing out my doubt :) Also can you provide a link where I can study about the concept you covered in first part of your answer in a much more depth ? – Backspace Dec 12 '14 at 07:38
  • Here you go:- http://www.programmingincpp.com/flush-the-output-stream-buffer.html http://support.microsoft.com/kb/94227 http://stackoverflow.com/questions/15042849/what-does-flushing-the-buffer-mean – ravi Dec 12 '14 at 07:43