# Comma operator in C?

73 views

See the following program, the output is coming as 10 dont know why can someone explain?

``````main()
{
int a,b;
a = 20;
b = 10;

a=a+b-(b,a);

printf("a = %d\n", a);
}
``````
posted Nov 13, 2014

+1 vote

ans : 10

Because in C, the comma "," operator associativity is form Left to Right.
So it process each one form Left to Right, and ignores them and finally tooks the the last one.

Take this as a example:

``````i = 5
j = i + (1, 2, 3, 4, 5);

j = 5 + 5 = 10   //i.e it process 1, 2, 3, 4, 5 and finally  tooks 5 from it (1, 2, 3, 4, 5)
``````
+1 vote

See the following examples

``````i = (a, b);         // stores b into i
i = a, b;           // stores a into i. Equivalent to (i = a), b;
i = a, b, c;        // stores a into i, discarding the unused b and c values
i = (a, b, c);      // stores c into i, discarding the unused a and b values
return 1, 2, 3;     // returns 3, not 1
return(1), 2, 3;    // returns 3, not 1
``````

Now your case is the first case so

``````a = 20+10-20 i.e. 10
``````
Similar Questions
``````#include <stdio.h>