The Comma Operator in C Programming Language

At first glance, you might not realize that a comma can be used in expressions  as an operator. The comma operator is at the bottom of the precedence totem pole, so to speak. In Chapter 5, “Program Looping,” you learned that inside a for statement you could include more than one expression in any of the fields by separating each expres- sion with a comma. For example, the for statement that begins

for ( i = 0, j = 100; i != 10; ++i, j -= 10 )

initializes the value of i to 0 and j to 100 before the loop begins, and increments the value of i and subtracts 10 from the value of j each time after the body of the loop is executed.

The comma operator can be used to separate multiple expressions anywhere that a valid C expression can be used. The expressions are evaluated from left to right. So, in the statement

while ( i < 100 )

sum += data[i], ++i;

the value of data[i] is added into sum and then i is incremented. Note that you don’t need braces here because just one statement follows the while statement. (It consists of two expressions separated by the comma operator.)

Because all operators in C produce a value, the value of the comma operator is that of the rightmost expression.

Note that a comma, used to separate arguments in a function call, or variable names in a list of declarations, for example, is a separate syntactic entity and is not an example of the use of the comma operator.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *