Is the execution order always the same in C / C ++

Will this code always produce the same result?

return c * (t /= d) * t * t + b;

So, I expect:

return ((c * (t / d) ^ 3) + b);

But I'm not sure if the compiler can interpret it as:

return ((c * t * t * (t / d)) + b)

I searched in the C standard, but could not find the answer, I know there x = x++is undefined, but here I am not sure because of ()around t /= d, which, I think, forces the compiler to compute this operator first.

+4
source share
3 answers

I searched in standard C but could not find an answer

What you are looking for is a point in the sequence .

Your expression

c * (t /= d) * t * t + b

does not contain sequence points, so subexpressions can be evaluated in any relative order.


, C, . , ++, . , .

2014-11-19 PDF: N4296

1.9 [intro.execution]

...

14 , , , , .

15 , , . [: , , . - end note] . - , (1.10), undefined. [. , . - ]

, ++ , , (, ;, ), .

() , ( ), undefined.

+6

:

return c * (t /= d) * t * t + b;

undefined C ( ++). , t ( (t /= d)), ( ), , t.

, UB, "" . , , .

gcc clang -Wall , UB. :

: 't' undefined [-Wsequence-point]

: 't' [-Wunsequenced]

+3

, , , :

return ((((c * (t /= d)) * t) * t) + b);

, , , . , .

, t , , . , t /= d, t, , .

In short, since you both read and write a variable in the same expression without a sequence point, you invoke undefined behavior .

+3
source

All Articles