11

これに対する決定的な答えが見つかりません: 次のコードには未定義の動作がありますか?

int x = 2;
x+=x+=x+=2.5;
4

2 に答える 2

0

For standard quotes see the other answers. It is likely to find one of two different behaviours in this case.

x += (x += 2);

May either be

x = 2 + 4 (= 6)

if the value of x on left side is evaluated before x+=2 or

x = 4 + 4 (= 8)

if the value of x for the left operator is determined afterwards.


-edit-

I know I not gonna get many fans on SO if I say I don't like those "anything may happen" claims very much. It is true that any compiler can declare itself standard conformant regardless of how the statement we discuss here is handled with respect to the value of x. Nevertheless, I think it doesn't mean that operator += may result in a wrong result or that parantheses may be ignored. Undefined behaviour is not the same as undefined behaviour in any other case.

It is bad to back on any expectation regarding undefined behaviour but in the above example i see good reasons for neglecting any possible outcome but 6 and 8.

In addition I actually suspect x to be 8 after the evaluation of int x=2; x += (x += 2); for most of the established compilers (clang, g++, vc, icpc...).

It is to be said again that you shouldn't rely on such behaviour but that doesn't mean that it is completely unpredictable.

于 2013-06-18T11:08:16.250 に答える