Comma Expressions
One of the specifics of C is that it allows using of comma as a sequence operator to form so-called comma expressions or sequences. Comma expression is a comma-delimited list of expressions – it is formally treated as a single expression so it can be used in places where an expression is expected. The following sequence:
expression_1, expression_2;
results in the left-to-right evaluation of each expression
, with the value and type of expression_2
giving the result of the whole expression. Result of expression_1
is discarded.
Binary operator comma (,
) has the lowest precedence and associates from left to right, so that a, b, c
is the same as (a, b), c
. This allows writing sequences with any number of expressions:
expression_1, expression_2, ... expression_n;
which results in the left-to-right evaluation of each expression
, with the value and type of expression_n
giving the result of the whole expression. Results of other expressions
are discarded, but their (possible) side-effect do occur.
For example:
result = ( a = 5, b /= 2, c++ ); /* returns preincremented value of variable c, but also intializes a, divides b by 2 and increments c */ result = ( x = 10, y = x + 3, x--, z -= x * 3 - --y ); /* returns computed value of variable z, and also computes x and y */
Note
Do not confuse comma operator (sequence operator) with comma punctuator which separates elements in a function argument list and initializator lists. To avoid ambiguity with commas in function argument and initializer lists, use parentheses. For example,
func(i, (j = 1, j + 4), k);
calls the function func
with three arguments (i, 5, k), not four.
What do you think about this topic ? Send us feedback!