-1

Can you explain the output of the following program:

#include <iostream>
using namespace std;

int main() 
{  
    int a=10;

    int x=(a++)+(++a)+(a++)+(a++)+(++a);

    cout<<x<<endl;
    x+= (++a);

    cout<<x<<" "<<a<<endl;
}

the output is:

62

78 16
bogatyrjov
  • 5,317
  • 9
  • 37
  • 61
  • possible duplicate of [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) –  Sep 21 '13 at 22:49

2 Answers2

0

A good example of why pre- and post-increment is not always a good idea. Applying the pre-and post-incrments in seqence to the initial vale of a (10) you get

This line:

int x=(a++)+(++a)+(a++)+(a++)+(++a);

becomes:

x = 10 + 12 + 12 + 13 + 15 // 62

While x+= (++a); becomes

x += 16;  // x=78
0

a++ increases the value of a after using the value of a whereas ++a increases the value before using its value. so in int x = x=(a++)+(++a)+(a++)+(a++)+(++a); the first a++ will use the value 10 and increase value of a to 11, now the next one, ++a, will increase the value of a from 11 to value 12 and then use it. so it becomes:

x = 10 + 12 + 12 + 13 + 15 = 62

and the value of x at this point is 15. next output can be explained similarly. Cheers!