是i = i ++真的是一个未定义的行为? [英] is i=i++ truly a undefined behavior?

查看:288
本文介绍了是i = i ++真的是一个未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

任何人都可以解释这些未定义的行为(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.

因为它是未定义的行为,根据标准( Wikipedia ),因此它甚至可以这样做:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆