在单个语句中的多个复合赋值:是未定义的行为还是不行? [英] Multiple compound assignments in a single statement: is it Undefined Behavior or not?

查看:181
本文介绍了在单个语句中的多个复合赋值:是未定义的行为还是不行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到一个明确的答案:以下代码是否有未定义的行为?

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


解决方案

行为未定义。让我们看看稍微简单的表达式:

  x + =(x + = 1)

在C ++ 11中,左侧 x 的值计算表达式(x + = 1)的值计算。这意味着 x 的值计算与 x (由于这是因为 = x <= x <= x <= x <= x <= x <= code> + = 运算符不相对于彼此排序(因为标准没有另外指定)。和1.9p15状态:


如果对标量对象的副作用相对于对同一标量对象的另一个副作用


在C ++ 03中,行为是未定义的,因为 x 被修改两次而没有中间序列点。


I can't find a definitive answer for this: does the following code have undefined behavior?

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

解决方案

The behavior is undefined. Let's look at the slightly simpler expression:

x += (x+=1)

In C++11, the value computation of the left x is unsequenced relative to the value computation of the expression (x+=1). This means that value computation of x is unsequenced relative to the assignment to x (due to x+=1), and therefore the behavior is undefined.

The reason for this is that the value computation of the two sides of the += operator are unsequenced relative to each other (as the standard doesn't specify otherwise). And 1.9p15 states:

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

In C++03 the behavior is undefined because x is modified twice without an intervening sequence point.

这篇关于在单个语句中的多个复合赋值:是未定义的行为还是不行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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