逗号运算符是否没有副作用? [英] Is comma operator free from side effect?

查看:1798
本文介绍了逗号运算符是否没有副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如对于这样的语句:

c += 2, c -= 1

这是真的,c + = 2将总是先评估,c在第二个表达式c- = 1将总是更新的值从表达式c + = 2?

Is it true that c += 2 will be always evaluated first, and c in second expression c-= 1 will always be updated value from expression c += 2?

推荐答案

是的,它是由标准保证的,只要逗号是非重载逗号运算符。引用n3290§5.18:

Yes, it is guaranteed by the standard, as long as that comma is a non-overloaded comma operator. Quoting n3290 §5.18:


从左到右的逗号操作符组。

The comma operator groups left-to-right.

表达式:

赋值语句

expression,assignment-expression

expression:
assignment-expression
expression , assignment-expression

用逗号分隔的一对表达式从左到右计算;左表达式是一个丢弃的
值表达式(第5条) 83 。与左表达式
相关联的每个值计算和副作用在之前排序每个值计算和与右表达式相关联的副作用。类型
和结果的值是右操作数的类型和值;结果是与其右操作数相同的值类别
,并且如果其右操作数是glvalue和位字段,则是位字段。

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded- value expression (Clause 5)83. Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field.

以及相应的脚注:


83 重载的逗号运算符是一个普通的函数调用;

83 However, an invocation of an overloaded comma operator is an ordinary function call; hence, the evaluations of its argument expressions are unsequenced relative to one another (see 1.9).



($)







$ b

因此,对于非重载逗号运算符,

在函数的参数之间不是逗号运算符。

The , between arguments to a function are not comma operators. This rule does not apply there either.

对于C ++ 03,情况类似:

For C++03, the situation is similar:


从左到右的逗号运算符组。

The comma operator groups left-to-right.


表达式:

assignment-expression

expression,assignment-expression

expression:
assignment-expression
expression , assignment-expression

用逗号分隔的一对表达式从左到右计算,左表达式的值为
。左值到右值(4.1),数组到指针(4.2)和函数到指针(4.3)标准转换不应用于左表达式。除了
临时值的破坏(12.2)之外,左表达式的所有副作用(1.9)在右表达式的求值之前执行。类型和
值的结果是右操作数的类型和值;如果其右操作数为,则结果为左值。

A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is discarded. The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conver- sions are not applied to the left expression. All side effects (1.9) of the left expression, except for the destruction of temporaries (12.2), are performed before the evaluation of the right expression. The type and value of the result are the type and value of the right operand; the result is an lvalue if its right operand is.

限制是相同的:不适用于重载的逗号运算符,参数列表。

Restrictions are the same though: does not apply to overloaded comma operators, or function argument lists.

这篇关于逗号运算符是否没有副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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