赋值子表达式的求值顺序 [英] Order of evaluation of assignment subexpressions

查看:75
本文介绍了赋值子表达式的求值顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11标准(5.17,expr.ass)指出

The C++11 standard (5.17, expr.ass) states that

在所有情况下,赋值都会在值计算之后进行排序 左右操作数的和,在计算值之前 赋值表达式.关于 不确定顺序的函数调用,复合操作 分配是一次评估

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation

这是否表示以下表达式:

Does this mean, that the expression:

int a = 1, b = 10;
int c = (a+=1) + (b+=1);

if ( c == 10+1+1+1 ) {
    printf("this is guaranteed");
} else {
    printf("not guaranteed"); 
}

将始终计算为c==23?

推荐答案

这始终得到保证,并且在规则之前进行排序 (或C ++ 11之前的序列点规则)不需要 确定这一点.在C ++中,每个(子)表达式都有两个重要的 生成的代码中的效果:它具有一个值(除非它是 类型void),则可能会有副作用.顺序 之前/顺序点规则会影响何时出现副作用 保证发生了;它们对价值没有影响 子表达式.例如,您的 value (a += 1)的值是赋值后a的值, 不管实际分配的时间是什么.

This has always been guaranteed, and the sequenced before rules (or the sequence point rules in pre-C++11) aren't need to determine this. In C++, each (sub-)expression has two important effects in the generated code: it has a value (unless it is of type void), and it may have side effects. The sequenced before/sequence point rules affect when the side effects are guaranteed to have taken place; they have no effect on the value of the sub-expressions. In your case, for example, the value of (a += 1) is the value a will have after the assignment, regardless of when the actual assignment takes place.

在C ++ 11中,保证对a进行实际修改 c修改之前的位置;在C ++ 11之前的版本中,没有 有关订单的保证.在这种情况下, 一致的程序无法看到这种差异,所以它 没关系(在c = (c += 1)这样的情况下, 这在C ++ 11之前的版本中是未定义的行为.)

In C++11, the actual modification of a is guaranteed to take place before the modification of c; in pre C++11, there was no guarantee concerning the order. In this case, however, there is no way a conforming program could see this difference, so it doesn't matter. (It would matter in cases like c = (c += 1), which would be undefined behavior in pre-C++11.)

这篇关于赋值子表达式的求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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