Why does a=(b++) have the same behavior as a=b++?
However, I expected the parentheses to have
b1
incremented before its value is assigned toa1
You should not have expected that: placing parentheses around an increment expression does not alter the application of its side effects.
Side effects (in this case, it means writing 11 into b1
) get applied some time after retrieving the current value of b1
. This could happen before or after the full assignment expression is evaluated completely. That is why a post-increment will remain a post-increment, with or without parentheses around it. If you wanted a pre-increment, place ++
before the variable:
a1 = ++b1;
Quoting from the C99:6.5.2.4:
The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.
You can look up the C99: annex C to understand what the valid sequence points are.
In your question, just adding a parentheses doesn't change the sequence points, only the ;
character does that.
Or in other words, you can view it like there's a temporary copy of b
and the side-effect is original b
incremented. But, until a sequence point is reached, all evaluation is done on the temporary copy of b
. The temporary copy of b
is then discarded, the side effect i.e. increment operation is committed to the storage,when a sequence point is reached.