Comma Operator

Preceding chapters have shown various ways to use the comma (,) in C programming. For instance, commas can separate multiple function arguments or variable declarations. In such cases the comma is not an operator in the formal sense but merely punctuation, like the semicolon that ends a statement.

Summary: The comma is used as punctuation and as an operator in C.

In C, the comma can also perform as an operator. The commas that separate multiple expressions determine the order in which the expressions are evaluated, and the type and value of the result that is returned. The comma operator causes expressions to be evaluated from left to right. The value and type of the result are the value and type of the rightmost operand.

For example, the statement

val = sample, sample = temp;

first assigns the value of sample to val, then assigns the value of temp to sample.

The comma operator often appears in for statements, where it can separate
multiple initializing expressions or multiple modifying expressions. The
FORLOOP1.C program from Chapter 3, “Flow Control,” demonstrates both uses. Here is the for statement from that program:

for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 )

printf( "a = %d \tb = %d\n", a, b );

The statement initializes two variables (a and b) and contains two modifying expressions (a = a / 2 and b = b * 2). Chapter 3 explains the FORLOOP1.C program in detail.