Node:The comma operator, Next:, Previous:Hidden operators and values, Up:Advanced operators

The comma operator

The comma operator (,) works almost like the semicolon ; that separates one C statement from another. You can separate almost any kind of C statment from another with a comma operator. The comma-separated expressions are evaluated from left to right and the value of the whole comma-separated sequence is the value of the rightmost expression in the sequence. Consider the following code example.

#include <stdio.h>

/* To shorten example, not using argp */
int main (int argc, char *argv[], char *envp[])
  int a, b, c, d;

  a = (b = 2, c = 3, d = 4);
  printf ("a=%d\nb=%d\nc=%d\nd=%d\n",
	  a, b, c, d);
  return 0;

The value of (b = 2, c = 3, d = 4) is 4 because the value of its rightmost sub-expression, d = 4, is 4. The value of a is thus also 4. When run, this example prints out the following text:


The comma operator is very useful in for loops. (See The flexibility of for, for an example.)