What does the comma operator , do? What does the comma operator , do? c c

What does the comma operator , do?


The expression:

(expression1,  expression2)

First expression1 is evaluated, then expression2 is evaluated, and the value of expression2 is returned for the whole expression.


I've seen used most in while loops:

string s;while(read_string(s), s.len() > 5){   //do something}

It will do the operation, then do a test based on a side-effect. The other way would be to do it like this:

string s;read_string(s);while(s.len() > 5){   //do something   read_string(s);}


The comma operator will evaluate the left operand, discard the result and then evaluate the right operand and that will be the result. The idiomatic use as noted in the link is when initializing the variables used in a for loop, and it gives the following example:

void rev(char *s, size_t len){  char *first;  for ( first = s, s += len - 1; s >= first; --s)      /*^^^^^^^^^^^^^^^^^^^^^^^*/       putchar(*s);}

Otherwise there are not many great uses of the comma operator, although it is easy to abuse to generate code that is hard to read and maintain.

From the draft C99 standard the grammar is as follows:

expression:  assignment-expression  expression , assignment-expression

and paragraph 2 says:

The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation. Then the right operand is evaluated; the result has its type and value. 97) If an attempt is made to modify the result of a comma operator or to access it after the next sequence point, the behavior is undefined.

Footnote 97 says:

A comma operator does not yield an lvalue.

which means you can not assign to the result of the comma operator.

It is important to note that the comma operator has the lowest precedence and therefore there are cases where using () can make a big difference, for example:

#include <stdio.h>int main(){    int x, y ;    x = 1, 2 ;    y = (3,4) ;    printf( "%d %d\n", x, y ) ;}

will have the following output:

1 4