i = i ++的行为真的不确定吗? [英] Is the behaviour of i = i++ really undefined?
问题描述
Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
根据c ++标准,
i = 3;
i = i++;
将导致不确定的行为.
我们使用术语未定义的行为",如果它可以导致一个以上的结果.但是在这里,无论计算顺序如何,i
的最终值都将为4,所以这真的不应该被称为未指定行为"吗?
We use the term "undefined behavior" if it can lead to more then one result. But here, the final value of i
will be 4 no matter what the order of evaluation, so shouldn't this really be called "unspecified behavior"?
推荐答案
短语"...无论计算顺序如何,i
的最终值将为4".编译器可以发出与之等效的东西:
The phrase, "…the final value of i
will be 4 no matter what the order of evaluation…" is incorrect. The compiler could emit the equivalent of this:
i = 3;
int tmp = i;
++i;
i = tmp;
或者这个:
i = 3;
++i;
i = i - 1;
或者这个:
i = 3;
i = i;
++i;
关于术语的定义,如果保证答案为4,则不会是未指定或未定义的行为,则将是已定义的行为.
As to the definitions of terms, if the answer was guaranteed to be 4, that wouldn't be unspecified or undefined behavior, it would be defined behavior.
就目前而言,根据标准(维基百科),它是未定义的行为,因此甚至可以免费这样做:
As it stands, it is undefined behaviour according to the standard (Wikipedia), so it's even free to do this:
i = 3;
system("sudo rm -rf /"); // DO NOT TRY THIS AT HOME … OR AT WORK … OR ANYWHERE.
这篇关于i = i ++的行为真的不确定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!