zzh1996 zzh1996 - 2 months ago 9
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;
printf("%d",(a=a+1)+(a=a+1)+(a=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
(++a)+(++a)+(++a)
, because the three
++
side effect can be run before all (++a) is evaluated.

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

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

R.. R..
Answer

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.