Its an undefined behavior. a
is getting modified multiple times within a sequence point.
Because its behavior is undefined, since the addition operands can be evaluated in any order. The compiler can evaluate the operands in any order because the addition operator is not a sequence point.
Because the addition operator is not a sequence point, strictly speaking the compiler is free to transform this expression:
a = b + c;
to this:
a = c + b;
But if the expressions have side effects, say, b++
and c++
, then the above statements may not be equivalent. Only when the flow of program execution reaches a sequence point, will all the side effects have occurred. For example:
callFunc(a, b, c);
Commas are not sequence points, so the compiler is free to evaluate the expressions a
, b
, and c
in any order. But a semicolon is a sequence point, meaning that by the time the flow of execution passes the semicolon, the side effects of the expressions a
, b
, and c
and the function call callFunc()
will have been completed.
Both examples have undefined behaviour.
In this case, it is because they are modifying the same object (a
) more than once without an intervening sequence point.
Sequence points within expressions are introduced by only a small number of operators: ,
, &&
, ||
and ?:
.
C++ Standard 03 - Chapter 5 : Expressions:
4.Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. 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. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.
In your example you have both:
- the value is modified more than once, violating the first rule
- the prior value is accessed to be modified, violating the second rule
Ergo: behavior is undefined