top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Comma operator in C?

+3 votes
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 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

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)
answer Nov 14, 2014 by Arshad Khan
+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 
answer Nov 13, 2014 by Salil Agrawal
Similar Questions
+3 votes

Here is working code on gcc compiler but I dont know the name of the symbol "--> ."

#include <stdio.h>
int main()
{
    int x = 10;
    while (x --> 0) // x goes to 0
    {
        printf("%d ", x);
    }
}
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...