-1

What's the difference here? I thought this 2 versions should be equal, but apparently they're not. Can you please explain how the first one works? Why does it print 222 instead of 122?

#include <iostream>
using namespace std;

int main() {
    int a = 1;
    /* #1: prints 222
    cout << a << (a = 2) << a << endl;
    */

    /* #2: prints 122
    cout << a;
    cout << (a = 2);
    cout << a << endl;
    */
    return 0;
}
Sfc
  • 9
  • 1
  • 1
    Read up on sequence points. – Marc Glisse Jun 06 '15 at 19:12
  • You are assigning `a` to 2 which modifies the value. The ostream evaluates the values before they are output. – Poriferous Jun 06 '15 at 19:16
  • @Poriferous is right. Let me explain little more. Compiler will read each line and modify value then it will work with result. In your code compiler read line a << (a=2) << a; here compiler reading line and you are changing value a=2 then nothing change on complete line. and after that compiler will print the result. So a has been modified to 2? then result will be 222. – Asif Mushtaq Jun 07 '15 at 03:52

1 Answers1

0

As far as I know you have no guarantee in which order sub expressions of a << expression are evaluated. In the first version, your compiler decides to do the assignment before the first output.

The second version however makes the order of operations explicit. The semicolon makes it clear that the print operation should occur before the assignment operation.

This is different to evaluations of e.g. binary operators, where thanks to short circuiting the order of side effects is left to right.

Marcus Riemer
  • 7,244
  • 8
  • 51
  • 76