在C ++中,赋值的一侧是否先于另一侧排序? [英] Is one side of an assignment sequenced before the other in c++?

查看:68
本文介绍了在C ++中,赋值的一侧是否先于另一侧排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解这是未定义的行为:

I understand that this is undefined behavior:

int i = 0;
int a[4];
a[i] = i++;  //<--- UB here

因为未定义左侧和右侧i的评估顺序(;是唯一的序列点).

because the order of evaluation of i for the left hand side and the right hand side are undefined (the ; is the only sequence point).

进一步推理,在我看来这将是未定义未指定的行为:

Taking that reasoning a step further it seems to me that this would be undefined unspecified behavior:

int i = 0;

int foo(){
    return i++;
}

int main(){
    int a[4];
    a[i] = foo();
    return 0;
}

就我所知,即使在=的右侧有一些序列点,仍然不确定 undefined 是否未指定是首先评估f()还是a[i].

Even though there are a few sequence points on the right hand side of the = as far as I understand it is still undefined unspecified whether f() or a[i] is evaluated first.

我的假设正确吗?当我在作业的左侧使用全局或静态变量而在任何情况下右手都不会对其进行修改时,我是否必须格外小心?

Are my assumptions correct? Do I have to take painstaking care when I use a global or static variable on the left hand side of an assignment that the right hand does not under any circumstances modify it?

推荐答案

a[i] = foo();

在这里,未指定是首先评估foo还是a[i].在新的C ++ 11措辞中,这两个评估是无顺序的.但是,这本身并不会导致不确定的行为.这是当对同一标量对象进行两次无序列访问时,其中至少有一个正在写入,而在此位置.这就是a[i] = i++;是UB的原因.

Here it is unspecified whether foo or a[i] is evaluted first. In the new C++11 wording, the two evaluations are unsequenced. That alone doesn't cause undefined behaviour, though. It is when there are two unsequenced accesses to the same scalar object, at least one of which is writing, where it does. That's why a[i] = i++; is UB.

这两个语句之间的区别在于,对foo()的调用确实引入了序列点. C ++ 11的措辞是不同的:相对于 calling 函数内部的其他求值,称为函数内部的执行是不确定地顺序.

The difference between these two statements is that a call to foo() does introduce a sequence point. C++11 wording is different: executions inside a called function are indeterminately sequenced with respect to other evaluations inside the calling function.

这表示foo中的a[i]i++之间存在部分排序.结果,a[0]a[1]都将被设置为0,但是程序定义良好.

This means there's a partial ordering between a[i] and i++ inside foo. As a result, either a[0] or a[1] will get set to 0, but the program is well defined.

这篇关于在C ++中,赋值的一侧是否先于另一侧排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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