Comma Operator ( , )

A comma expression contains two operands separated by a comma. Although the compiler evaluates both operands, the value of the right operand is the value of the expression. The left operand is evaluated, possibly producing side effects, and the value is discarded. The result of a comma expression is not an lvalue.

Both operands of a comma expression can have any type. All comma expressions have left-to-right associativity. The left operand is fully evaluated before the right operand.

In the following example, if omega has the value 11, the expression increments delta and assigns the value 3 to alpha:

alpha = (delta++, omega % 4);

Any number of expressions separated by commas can form a single expression. The compiler evaluates the leftmost expression first. The value of the rightmost expression becomes the value of the entire expression.

For example, the value of the expression:

intensity++, shade * increment, rotate(direction);

is the value of the expression:

rotate(direction)

The primary use of the comma operator is to produce side effects in the following situations:

To use the comma operator in a context where the comma has other meanings, such as in a list of function arguments or a list of initializers, you must enclose the comma operator in parentheses. For example, the function

f(a, (t = 3, t + 2), c);

has only three arguments: the value of a, the value 5, and the value of c. The value of the second argument is the result of the comma expression in parentheses:

t = 3, t + 2

which has the value 5.



Operator Precedence and Associativity
Expressions and Operators
Types of Expressions


Operator Precedence and Associativity Table
Primary Operators
Unary Operators
Binary Operators
Conditional Operator
Assignment Operators
Examples Using the Comma Operator ( , )