BLOG DETAILS

More about comma operator in C/C++ Language

  • By Suresh Kulahry
  • |
  • June 13, 2018

We know that the comma operator (,) is used to separate the declaration of variables or two or more expressions. Remember, the comma operator has the lowest priority among all the operators, and the associativity of the comma operator is from left to right.

Example:

  • int a,b,c;
  • int a=25,b=36,c;

The comma operator works as an operator when it is used in expressions. The expression is evaluated from left to right and the comma operator returns the value of the rightmost operand when multiple comma operators are used inside an expression.

For example, consider this expression,

sum=(a=2,b=3,c=5,a+b+c);

Here we have combind 4 expressions. Initially 2 is assigned to the variable a, then 3 is assigned to variable b, 5 is assigned to variable c and after this a+b+c is evaluated  which becomes the value of whole expression and assigned to variable sum.

For example without the use of comma operator, the above task would have been done in four statements.

  1. a=2;
  2. b=3;
  3. c=5;
  4. sum=a+b+c;

Programming Examples-1

void main()
{
        int num;
        num=(36,25,41);
        printf("%d",num);
}

OUTPUT

41

Programming Examples-2

void main()
{
        int num;
        num=36,25,41;
        printf("%d",num);
}

OUTPUT

36

Explanation:

We know that the precedence of the comma operator is the lowest among the entire operator set. So the assignment operator takes precedence over the comma and the expression “num=36, 25, 41;″ becomes equivalent to “(num = 36), 25, 41″. That is why we get the output as 36.

Programming Examples-3

void main()
{
        int num=36,25,41;
        printf("%d",num);
}

OUTPUT

Compile Time Error (Declaration Termination Incorrectly)

Programming Examples-4

void main()
{
        clrscr();
        printf("Suraku","Academy");
        printf(("Suraku","Academy"));
}

OUTPUT

SurakuAcademy