The code under consideration is, when modernized and given some missing spaces:
#include <stdio.h>
int main(void)
{
int a = 1, b = 2, c = 3;
printf("%d\n", a += (a += 3, 5, a));
return 0;
}
My initial reaction was “dup of Why are these constructs undefined behaviour”, even though that is primarily about ++
and --
operators which are more often seen in such questions.
A second glance notes that there a comma operators in (a += 3, 5, a)
and these impose sequence points. On its own, this much of the expression is fine. If it were used in b += (a += 3, 5, a)
, there would be no problem. The text of the question asks about just (a += 3, 5, a)
.
Of course, the , 5
does nothing useful. And when that’s eliminated, the only reason to use (a += 3, a)
is to put a sequence point between the addition and the a
. However, there are no circumstances I can think of where you could legitimately need that sequence point.
The more complex issue is whether the evaluation of the LHS of a += (a += 3, 5, a)
is properly sequenced with the RHS. It is undefined behaviour because although there are sequence points in the RHS expression, there isn’t a sequence point between the evaluation of the LHS and RHS of the overall expression.
Remember that the compound assignment operator +=
behaves more or less as:
a += x;
a = a + x;
The difference is that the expression on the LHS (a
in this example) is only evaluated once. In this case, there’s no problem. If the code were more complex, this detail matters:
array[index++].member[subindex++] += 23;
Now it is crucial that the LHS is only evaluated once!
Summary
The code in the question is tricky code and, because it has undefined behaviour, it should be avoided in production code.
I wonder why b
and c
are in the question at all; they’re unused variables. So much confusion in so little code!
Rule of thumb: Avoid multiple increments, decrements and compound assignment operators in a single expression.
Advanced rule of thumb (for experts only): don’t apply multiple increments, decrements or compound assignment operators to the same variable in a single expression.
If you know enough to know when you can safely break the rules (?:
), then you don’t necessarily need to follow the rules of thumb. Until then, avoid over-using these operators.
1
solved Explain the output of the following C program?