++ + ++

Hi.
Why does the following code print
2 2?
1
2
3
4
5
    int a=0,  b=0 ;
    b=a++ + ++a;
    cout << a << ' '  << b << endl;
    while(1);
    return 0;
There are plenty of posts like this on the forum already, doing multiple pre and post increment/decrement operations in the same expression is undefined behaviour.
Last edited on
But what is the logic?
because a and b are both 2
It might print 2 2. It might print 2 3. Or it might print something entirely different.

What you are doing has undefined behavior, which means anything is game. As Zephilinox said, you should never ever do this.



Though for academic reasons, if you are getting 2 2 as output, the compiler is probably doing this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
b = a++ + ++a;

/*
compiler must do the following

1) 'a++' must be evaluated before the '+' operator is
2) '++a' must be evaluated before the '+' operator is
3) '+' must be evaluated before the '=' operator is
4) 'a++' must increment a by one.  It also must return the previous value of a
5) '++a' must increment a by one.  It also must return the new value of a
*/

/*
How the compiler may be interpretting that code:
*/
++a;      // evaluate and perform the prefix increment to 'a'.  a=1, b=0
b = a + a;  // evaluate the + and = operators normally.  a=1, b=2
a++;     // evaluate the postfix increment.  a=2, b=2 


Hence you get the "2 2" output.

But again... this is entirely compiler/version/phase of the moon dependent and different people running this code are likely to get different results, so you should never ever ever do anything like this in actual code.
hooshdar3 wrote:
But what is the logic?

No logic. It's undefined.
Topic archived. No new replies allowed.