 |
Comma operator and punctuator (',') |
The comma, used as a punctuator, separates the elements of a function argument list,
the elements in array or struct initializers, or the variables in a data declaration.
The comma is also used as an operator in comma expressions. Mixing the two
uses of comma is legal, but you must use parentheses to distinguish them.
When used as an operator, the comma operator uses the following syntax:
expr1, expr2
The left operand expr1 is evaluated as a void expression
(i.e. it is ignored if not contain side effects), then expr2 is evaluated
to give the result and type of the comma expression. So, the result is just expr2.
By recursion, the expression
expr1, expr2, ..., ExprN
results in the left-to-right evaluation of each Expr-i, with the value and type
of ExprN giving the result of the whole expression. Comma operator is usually used
in for-loops for multiple initializations. For example,
for (i = 0, j = 1024; i + j < 5; i++, j /= 2) ...
It also may be used to avoid making compound statements in simple conditional statements.
For example,
if (x > 10) i = 1, j = 2, k = 3;
have the same effect as
if (x > 10)
{
i = 1; j = 2; k = 3;
}
To avoid ambiguity with the commas used in function argument and initializer
lists, parentheses must be used. For example,
func(i, (j = 1, j + 4), k);
calls 'func'
with three arguments, not four. The arguments are
'i'
, '5'
, and 'k'
.