C/C ++中的未定义行为:i ++ + ++ i与++ i + i ++ [英] Undefined behavior in c/c++: i++ + ++i vs ++i + i++
问题描述
想象一下,我们有下面的代码:
Imagine that we have the code below:
int i = 1;
int j = i++ + ++i;
我知道这是一个未定义的行为,因为在分号(它是一个序列点)之前,i
的值已多次更改.这意味着即使运算符plus的优先级是从左到右,编译器也可能有两种可能性:
I know that this is a Undefined Behavior, because before the semicolon, which is a sequence point, the value of i
has been changed more than once. It means that the compiler may have two possibilities even if the precedence of operator plus is Left-to-Right:
案例1)
- 取
i++
的值---i
的值为1 - 取
++i
的值---i
的值为2 - 将运算符加,并将结果3分配给
j
,并产生i++
的副作用(此步骤的顺序也未定义,但我们不在乎,因为它不会改变结果)
- take the value of
i++
--- value ofi
is 1 - take the value of
++i
--- value ofi
is 2 - do the operator plus and assign the result which is 3 to
j
and do the side effect ofi++
(the order of this step is undefined too but we don't care because it won't change the result)
案例2)
- 取
i++
的值---i
的值为1 - 做
i++
的副作用---i
的值为2 - 取
++i
的值---i
的当前值为3 - 将运算符加,并将结果4分配给
j
- take the value of
i++
--- value ofi
is 1 - do the side effect of
i++
--- value ofi
is 2 - take the value of
++i
--- current value ofi
is 3 - do the operator plus and assign the result which is 4 to
j
如果这里没有问题,我有个问题:
If nothing is wrong here, I have a question:
int j = ++i + i++;
上面的代码仍然是未定义的行为吗?
Is the code above still an Undefined Behavior?
我认为只有一种可能性:
In my opinion, there is only one possibility:
- 做
++i
的副作用---i
的值为2 - 取
i++
的值---i
的值为2 - 将运算符加,并将结果4分配给
j
,并产生i++
的副作用(此步骤的顺序也未定义,但我们不在乎,因为它不会改变结果)
- do the side effect of
++i
--- value ofi
is 2 - take the value of
i++
--- value ofi
is 2 - do the operator plus and assign the result which is 4 to
j
and do the side effect ofi++
(the order of this step is undefined too but we don't care because it won't change the result)
我说得对吗?
顺便说一句,我已经阅读了此链接:
未定义的行为和序列点
Btw I've read this link:
Undefined behavior and sequence points
推荐答案
int j = ++i + i++;
仍然是不确定的行为,因为++i
和i++
可以在某些CPU中的多个管道中同时处理,这将导致不可预测的结果.
is still undefined behavior since ++i
and i++
can be processed simultaneously in multiple pipelines in some CPUs, which will lead to unpredictable results.
这篇关于C/C ++中的未定义行为:i ++ + ++ i与++ i + i ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!