-6

I do not understand why the output of following program is 63:

#include <iostream>

int main() {
  int a = 20;
  a += a + ++a;
  std::cout << a;
} 

I was expecting it to be 61. What exactly a += a + ++a; does?

LihO
  • 41,190
  • 11
  • 99
  • 167
user2747954
  • 97
  • 1
  • 5
  • 16

3 Answers3

3

Standard says: "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression" (5 Expressions, §4), i.e. the following:

a += a +  ++a 

yields undefined behavior just like:

a = ++a;

does already. It also says: "the prior value shall be accessed only to determine the value to be stored", i.e. if you want to change a, you can use a in the same expression just to retrieve the previous value:

a = a + 1; // OK

... "otherwise the behavior is undefined."

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Thank you, you mean to say this expression may generate unpredictable output, meaning sometime 63 sometime 21 and may be sometime 20. Can you pls explain little more – user2747954 Sep 26 '13 at 17:09
  • @user2747954: Undefined behavior generally means that anything can happen. This kind of behavior might vary depending on your compiler, the environment that you're using... sometimes it can result in code that works perfectly in 99.9% cases making a ticking bomb waiting for that 0.1%... if you know something produces undefined behavior, ***avoid it***. – LihO Sep 26 '13 at 17:13
1

You're triggering undefined behavior and there is no 'correct' answer. Your compiler can chose what order to evaluate the arguments of the plus operator.

yan
  • 20,644
  • 3
  • 38
  • 48
0

it looks like ++a is evaluating before the rest of the expression, so it's as though a is 21` in a statement like

a += a + a;

at any rate, don't use ++a inside of an arithmetic expression like that anyway. It's confusing for people, and is probably undefined behavior