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

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

问题描述

C ++ 11标准< a>(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

这意味着,表达式:

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

will always evaluate to c==23?

推荐答案

这一直是保证,并且在规则之前排序
点规则在pre-C ++ 11)不需要
确定这个。在C ++中,每个(子)表达式在生成的代码中有两个重要的
效果:它有一个值(除非是
类型 void ),它可能有副作用。在序列点规则之前的序列化
影响当副作用是保证发生的
时;它们对子表达式的值
没有影响。例如,在您的情况下,(a + = 1) value
是值 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天全站免登陆