++ + ++

Oct 20, 2012 at 9:09am
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;
Oct 20, 2012 at 10:22am
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 Oct 20, 2012 at 10:23am
Oct 20, 2012 at 10:51am
But what is the logic?
Oct 20, 2012 at 11:03am
because a and b are both 2
Oct 20, 2012 at 11:13am
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.
Oct 20, 2012 at 11:13am
hooshdar3 wrote:
But what is the logic?

No logic. It's undefined.
Oct 20, 2012 at 12:08pm
Topic archived. No new replies allowed.