Uses of C comma operator

Viewed 22475

You see it used in for loop statements, but it's legal syntax anywhere. What uses have you found for it elsewhere, if any?

20 Answers

For me the one really useful case with commas in C is using them to perform something conditionally.

  if (something) dothis(), dothat(), x++;

this is equivalent to

  if (something) { dothis(); dothat(); x++; }

This is not about "typing less", it's just looks very clear sometimes.

Also loops are just like that:

while(true) x++, y += 5;

Of course both can only be useful when the conditional part or executable part of the loop is quite small, two-three operations.

qemu has some code that uses the comma operator within the conditional portion of a for loop (see QTAILQ_FOREACH_SAFE in qemu-queue.h). What they did boils down to the following:

#include <stdio.h>

int main( int argc, char* argv[] ){
  int x = 0, y = 0;

  for( x = 0; x < 3 && (y = x+1,1); x = y ){
    printf( "%d, %d\n", x, y );
  }

  printf( "\n%d, %d\n\n", x, y );

  for( x = 0, y = x+1; x < 3; x = y, y = x+1 ){
    printf( "%d, %d\n", x, y );
  }

  printf( "\n%d, %d\n", x, y );
  return 0;
}

... with the following output:

0, 1
1, 2
2, 3

3, 3

0, 1
1, 2
2, 3

3, 4

The first version of this loop has the following effects:

  • It avoids doing two assignments, so the chances of the code getting out of sync is reduced
  • Since it uses &&, the assignment is not evaluated after the last iteration
  • Since the assignment isn't evaluated, it won't try to de-reference the next element in the queue when it's at the end (in qemu's code, not the code above).
  • Inside the loop, you have access to the current and next element
Related