zzh1996 zzh1996 - 3 months ago 11
C Question

The result of (a=a+1)+(a=a+1)+(a=a+1) in c?

When I compile this code with gcc and run

int a=1;

I expect the result to be 2+3+4=9, but the output is 10.

I know that there is undefined behavior in
, because the three
side effect can be run before all (++a) is evaluated.

But I think the value of
is exactly what
is after the assignment is evaluated. So the compiler cannot process three
first and use the value in variable
as the value of
after all

I want to know where is wrong according to the c standard.

R.. R..

The assignment operator is not a sequence point. Assuming a is just an identifier (e.g. not a macro argument that might expand to something more complicated) and does not have an atomic type (C11), a=a+1 is identical in semantics to ++a.

I wanted to mark this question as a duplicate of one of the hundreds of ++ operator sequence-point questions, but it seems your question is about why this form isn't different.