6.9 – Comma operator in C language

by subbu on September 29, 2013

Comma operator in C language:

It is a special operator in C language used to link related expressions together. List of expressions separated with comma operator evaluates from left to right. Right most expression is the value of expression.

#include<stdio.h>
int main()
{
 int x,y,z;
 x=10,y=20,z=x+y;
 printf("Sum %d",z);
 return 0;
}

Output:
Sum 30

Here list of expressions are separated with comma and evaluated from left to right. Here comma worked like a separator rather an operator.

#include<stdio.h>
int main()
{
 int x=12,34,45,67;
 printf("%d",x);
 return 0;
}

Output:
In function ‘main’:
4:10: error: expected identifier or ‘(‘ before numeric constant
int x=12,34,45,67;

Here compiler treats comma as separator and throws a syntax error

#include<stdio.h>
int main()
{
 int x;
 x=12,34,45,67;
 printf("%d",x);
 return 0;
}

Output:
12

Comma operator get least priority comparatively with assigning (=) operator. The result of statement “x=12,34,45,67;” would be “(x=12),34,45,67;”. Hence 12 is assigned to x and the result is printed as 12.

#include<stdio.h>
int main()
{
 int x;
 x=(12,34,45,67);
 printf("%d",x);
 return 0;
}

Output:
67

As the list of values is placed in a parenthesis, the comma operator gets explicit priority. Hence, right most value in the list 67 is assigned to the variable x

#include<stdio.h>
int main()
{
 int x,y,z;
 z=(x=10,y=20,x+y);  /* x+y is assigned to z */
 printf("Sum %d",z);
 return 0;
}

Output:
Sum 30

Here related expressions are separated with comma and evaluated from left to right. As the value of expression is the result of right most expression, sum of x and y that is x+y is assigned to z.

#include<stdio.h>
int main()
{
 switch(4,5,2,3)
 {
  case 2:
   printf("Two");
   break;
  case 3:
   printf("Three");
   break;
  case 4:
   printf("Four");
   break;
  case 5:
   printf("Five");
   break;
  default:
   printf("None");
 }
 return 0;
}

Output:
Three

Here, the right most value 3 would be the value of switch selection constant.

#include<stdio.h>
int main()
{
 do{
     printf("Hello World");
   }while(5,3,0);
 return 0;
}

Output:
Hello World

Here, the right most value 0 would be the condition to the do-while iteration statement. As 0 is considered as false, the loop terminates after the completion of first execution

Previous post:

Next post: