C doesn’t force left-to-right evaluation of arithmetic expressions - each of a = 3
, b = a + 2
, and a = 2
may be evaluated in any order (they are said to be unsequenced with respect to each other). Since two of those expressions modify the value of a
, the result of b = a + 2
can vary based on the compiler, optimization settings, even the surrounding code - the result could be 7
, 5
, 2
, or something else completely.
The behavior of modifying a
multiple times and using it in a value computation without an intervening sequence point is undefined, meaning the compiler isn’t required to handle the situation in any particular way. It may give you the result you expect, but it doesn’t have to. The result doesn’t have to be consistent from build to build, or even from run to run.
This should give the results you would expect based on a left-to-right reading of your expression.
a = 3;
b = a + 2; // b = 5
c = a + b - 2; // c = 6
a = 2;