顺序评估运算符Sequential-Evaluation Operator

顺序计算运算符(也称为“逗号运算符”)按从左到右的顺序计算其两个操作数。The sequential-evaluation operator, also called the "comma operator," evaluates its two operands sequentially from left to right.

语法Syntax

expression:expression:
assignment-expressionassignment-expression

expression , assignment-expressionexpression , assignment-expression

顺序计算运算符的左操作数的计算结果为 void 表达式。The left operand of the sequential-evaluation operator is evaluated as a void expression. 该运算的结果与右操作数具有相同的值和类型。The result of the operation has the same value and type as the right operand. 所有操作数都可以是任意类型。Each operand can be of any type. 顺序计算运算符在其操作数之间不执行类型转换,也不产生左值。The sequential-evaluation operator does not perform type conversions between its operands, and it does not yield an l-value. 第一个操作数后有一个序列点,这意味着来自左操作数的计算的所有副作用在开始右操作数的计算前已完成。There is a sequence point after the first operand, which means all side effects from the evaluation of the left operand are completed before beginning evaluation of the right operand. 有关详细信息,请参阅序列点See Sequence Points for more information.

顺序计算运算符通常用于计算只允许有一个表达式的上下文中的两个或多个表达式。The sequential-evaluation operator is typically used to evaluate two or more expressions in contexts where only one expression is allowed.

逗号可以在上下文中用作分隔符。Commas can be used as separators in some contexts. 但是,您务必小心,不要混淆将逗号用作分隔符与将逗号用作运算符;这两种用法完全不同。However, you must be careful not to confuse the use of the comma as a separator with its use as an operator; the two uses are completely different.

示例Example

以下示例演示顺序计算运算符:This example illustrates the sequential-evaluation operator:

for ( i = j = 1; i + j < 20; i += i, j-- );  

在本示例中,for 语句的第三个表达式的每个操作数都是单独计算的。In this example, each operand of the for statement's third expression is evaluated independently. 首先计算左操作数 i += i,然后计算右操作数 j--The left operand i += i is evaluated first; then the right operand, j--, is evaluated.

func_one( x, y + 2, z );  
func_two( (x--, y + 2), z );  

在对 func_one 的函数调用中,将传递以逗号分隔的三个参数:xy + 2zIn the function call to func_one, three arguments, separated by commas, are passed: x, y + 2, and z. 在对 func_two 的函数调用中,圆括号强制编译器将第一个逗号解释为顺序计算运算符。In the function call to func_two, parentheses force the compiler to interpret the first comma as the sequential-evaluation operator. 此函数调用将两个参数传递给 func_twoThis function call passes two arguments to func_two. 第一个参数是顺序计算运算 (x--, y + 2) 的结果,具有表达式 y + 2 的值和类型;第二个参数为 zThe first argument is the result of the sequential-evaluation operation (x--, y + 2), which has the value and type of the expression y + 2; the second argument is z.

请参阅See Also

逗号运算符:,Comma Operator: ,