Comma Operator

The comma operator allows grouping two statements where one is expected.

Syntax

  • expression :
    assignment-expression
    expression , assignment-expression

The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.

Consider the expression

e1 , e2

The type and value of the expression are the type and value of e2; the result of evaluating e1 is discarded. The result is an l-value if the right operand is an l-value.

Where the comma has special meaning (for example in actual arguments to functions or aggregate initializers), the comma operator and its operands must be enclosed in parentheses. Therefore, the following function calls are not equivalent:

// Declare functions:
void Func( int, int );
void Func( int );

Func( arg1, arg2 );    // Call Func( int, int )
Func( (arg1, arg2) );  // Call Func( int )

This example illustrates the comma operator:

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

In this example, each operand of the for statement’s third expression is evaluated independently. 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 );

In the function call to func_one, three arguments, separated by commas, are passed: x, y + 2, and z. In the function call to func_two, parentheses force the compiler to interpret the first comma as the sequential-evaluation operator. This function call passes two arguments to func_two. The 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.