Thursday, July 11, 2013

The Comma Operator in C

Comma is generally used to separate two things. In C, along with separating two things, we also use comma as an operator along with separator.

If we use comma as an operator, then the expression evaluates to the right sub-expression.

For example,
x=(a,b);
Then x is assigned the value of b.Here parenthesis are must because comma operator has the lowest precedence than that of assignment. So parenthesis should be used to evaluate the expression.

Consider the following example program,

  1. #include<stdio.h>
  2. main()
  3. {
  4. printf("%d", (3,5));
  5. return 0;
The output of the above program is as expected the right sub expression i.e., 5

If we give more than one value and more comma separators, then what happens??
If we give the Line 4 as printf("%d", (1,2,3,4,5)), what would be result???
It considers all the values and assigns the right most value i.e., 5.

Thus comma operator is used in C.