2

The code is simple:

int Change(int& a)
{
   a = 4;
  return a;
}

int main()
{
  int a = 10;
  cout << Change(a) << a;
}

In C-Free : the output : 4 4

In VS2008 : the output : 4 10

Why? As I have learned, I think 4 4 is right.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Fanl
  • 1,491
  • 2
  • 11
  • 15
  • 2
    Both are right. And `cout` has nothing to do with it. Every function is like `operator<<` is in this regard. – chris Sep 28 '14 at 04:36
  • @chris could you detail a bit more please? Do you mean this behaviour is compiler-dependent? – Javi Sep 28 '14 at 04:39
  • 2
    Here: http://stackoverflow.com/questions/3457967/what-belongs-in-an-educational-tool-to-demonstrate-the-unwarranted-assumptions-pe/3458842#3458842. I also strongly advise not using and changing the same variable in two different parts of the same expression. That becomes undefined behaviour way too easily (e.g., `i + i++`). – chris Sep 28 '14 at 04:41
  • You can also refer to this: http://stackoverflow.com/questions/14809978/order-of-execution-in-operator – Hemant Gangwar Sep 28 '14 at 04:42
  • 3
    This reference will also help: http://en.cppreference.com/w/cpp/language/eval_order . Check the `undefined behavior` section and you'll also find an example directly related to your question. – Michael Petch Sep 28 '14 at 04:50

1 Answers1

0

Simply put, there is no rule that guarantees that "4 4" is right. Same goes for "4 10".

As others have mentioned in the comments you have a case of undefined behaviour here. Even if this would be defined behaviour, code like this is difficult to understand. So I recommend to do

cout << Change(a);
cout << a;

or

int b = a;
cout << Change(a);
cout << b;

whatever you really want to do.

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52