Comma Operator in C programming Language | Comma operator in depth analysis with examples

Spread the love

Comma ( , ) token in C :

  • The Comma ( , ) is used as Operator and Separator in C programming language.
  • Comma act as separator in variables declarations, function calls, function definitions.
  •  Comma operator is binary operator, Means it works on two operands
  • Comma operator separates the Expressions. the separated expressions are evaluated from Left to right.

Comma As Separator :

int a=1, b=2, c=3, d=4;
Here Comma act as separator.

Comma As Operator  :

The Comma operator Separates the Expressions. the separated expressions are evaluated from left to right and value of the rightmost expression is the type and value of the compound expression. here is the few examples of Comma operator.

program 1: Understanding Comma Operator in C programming Language :

  1. #include<stdio.h>
  2. int main()
  3. {
  4.         int a=1, b=2, c ; // here comma is Separator
  5.         c = a , b ;      // here comma is Operator
  6.         printf(“a = %d b = %d c = %d”,a,b,c);
  7.         return 0;
  8. }
output :

a = 1 b = 2 c = 1

In Above program statement  c = a , b ; contains  comma operator, Initially a value is assigned to c. so c value become 1 and then b is discarded.
lets take a other scenario of above program with small modification

Program 2 : Understanding the Behavior of Comma operator in C programming Language

  1. #include<stdio.h>
  2. int main()
  3. {
  4.         int a=1, b=2, c ;  // here comma is Separator
  5.         c = ( a , b );     // here comma is Operator
  6.         printf(“a = %d b = %d c = %d”,a,b,c);
  7.         return 0;
  8. }

output :

a = 1 b = 2 c = 2

See the output of second program c contains 2 that means value of b.because of the parenthesis around a and b.(please look carefully second program contains parenthesis in line no 5).
c = ( a , b) ;

If multiple expressions are separated by Comma in a group (group means covered by parenthesis), then all the expressions are evaluated from left to right and group value is the Right most expression value.

So above expression is group of expressions so rightmost expression value is assigned to c.

Related Posts :


Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer and an Open Source enthusiast, Presently working as a Software Engineer. Apart from that, I love to explore new technologies and things.

You may also like...

Leave a Reply