1

The following code prints 7. It increments value of a, but b remains unaffected. Post increment operator is not supposed to increment first and then use the value which it has done in this case. It should be the other way around. Why this change in behaviour? Also, and perhaps more importantly, why is b not pre-incremented?

int  main() {

  int a=5, b=2;
  printf("%d", a+++b);

}
micnic
  • 10,915
  • 5
  • 44
  • 55

2 Answers2

1

You have a well defined behavior. Where

a++ + b = 5 +2 = 7

If you have a pre-incrementor operator like

printf("%d\n",++a+b);

Then the output would be 8

The ++ operator has higher precendence than the + unary plus operator so the evaluation from left to right of

a+++b will happen

a++ + b which will fetch you 7

Post-incrementation is done by taking the value of your variable first which in this case is 5 so

a= 5 and b=2

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

In your code a is added to b and then it is incremented

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63