C/C ++中的未定义行为:i ++ + ++ i与++ i + i ++ [英] Undefined behavior in c/c++: i++ + ++i vs ++i + i++

查看:200
本文介绍了C/C ++中的未定义行为:i ++ + ++ i与++ 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)

  1. i++的值--- i的值为1
  2. ++i的值--- i的值为2
  3. 将运算符加,并将结果3分配给j,并产生i++的副作用(此步骤的顺序也未定义,但我们不在乎,因为它不会改变结果)
  1. take the value of i++ --- value of i is 1
  2. take the value of ++i --- value of i is 2
  3. do the operator plus and assign the result which is 3 to j and do the side effect of i++ (the order of this step is undefined too but we don't care because it won't change the result)

案例2)

  1. i++的值--- i的值为1
  2. i++的副作用--- i的值为2
  3. ++i的值--- i的当前值为3
  4. 将运算符加,并将结果4分配给j
  1. take the value of i++ --- value of i is 1
  2. do the side effect of i++ --- value of i is 2
  3. take the value of ++i --- current value of i is 3
  4. 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:

  1. ++i的副作用--- i的值为2
  2. i++的值--- i的值为2
  3. 将运算符加,并将结果4分配给j,并产生i++的副作用(此步骤的顺序也未定义,但我们不在乎,因为它不会改变结果)
  1. do the side effect of ++i --- value of i is 2
  2. take the value of i++ --- value of i is 2
  3. do the operator plus and assign the result which is 4 to j and do the side effect of i++ (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++;

仍然是不确定的行为,因为++ii++可以在某些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屋!

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