How to use comma operator in different program statements ?

How to use comma operator in different program statements ?

  • Comma Operator have lowest priority in C Programming Operators.
  • We have mentioned all possible operations that can be performed on comma operator.
  • All uses of comma operator are summarized below -

Possible uses of Comma Operator :

  1. Using Comma Operator along with Assignment
  2. Using Comma Operator with Round Braces.
  3. Using Comma Operator inside printf statement
  4. Using Comma Operator inside Switch cases.
  5. Using Comma Operator inside For Loop
  6. Using Comma Operator for multiple declaration.

Verity 1 : Using Comma Operator along with Assignment

#include<stdio.h>
int main()
{
          int i;
          i = 1,2,3;
          printf("i:%d\n",i);
          return 0;
}

Output :

i:1

Explanation :

i = 1,2,3;
  • Above Expression contain 3 comma operator and 1 assignment operator.
  • If we check precedence table then we can say that “Comma” operator has lowest precedence than assignment operator
  • So Assignment statement will be executed first .
  • 1 is assigned to variable “i”.

Verity 2 : Using Comma Operator with Round Braces

#include<stdio.h>
int main()
{
          int i;
          i = (1,2,3);
          printf("i:%d\n",i);
          return 0;
}

Output :

i:3

Explanation :

i = (1,2,3);
  • Bracket has highest priority than any operator.
  • Inside bracket we have 2 comma operators.
  • Comma operator has associativity from Left to Right.
  • Comma Operator will return Rightmost operand
i = (1,2,3)
==> 1,2 will return 2
==> 2,3 will return 3
==> means (1,2,3) will return 3
==> Assign 3 to variable i.

Verity 3 : Using Comma Operator inside printf statement

#include<stdio.h>
#include< conio.h>
void main()
{
clrscr();
printf("Computer","Programming");
getch();
}

Output :

Computer

Verity 4 : Using Comma Operator inside Switch cases.

#include<stdio.h>
#include< conio.h>
void main()
{
 int choice = 2 ;
 switch(choice)
 {
  case 1,2,1:
        printf("\nAllas");
        break;
  case 1,3,2:
        printf("\nBabo");
        break;
  case 4,5,3:
        printf("\nHurray");
        break;
 }
}

Output :

Babo

Verity 5 : Using Comma Operator inside For Loop

#include<stdio.h>
int main()
{
int i,j;
for(i=0,j=0;i<5;i++)
  {
  printf("\nValue of J : %d",j);
  j++;
  }
return(0);
}

Output :

Value of J : 0
Value of J : 1
Value of J : 2
Value of J : 3
Value of J : 4

Verity 6 : Using Comma Operator for multiple Declaration

#include<stdio.h>
int main()
{
int num1,num2;
int a=10,b=20;
return(0);
}

Note : Use of comma operator for multiple declaration in same statement.