3

I am running a code snippet. But I am not able to understand the code and the output that it is producing.

#include <stdio.h>
int main()  
{ 
  int a, b,c, d;    
  a=3;    
  b=5;    
  c=a,b;    
  d=(a,b);      
  printf("c = %d" ,c);    
  printf("\nd = %d" ,d);    
  return 0;
}  

The output of this program is:

c=3
d=5

I am not getting how the output is coming?

Jainendra
  • 24,713
  • 30
  • 122
  • 169

3 Answers3

9
  1. When you have a comma, the expression is evaluated as the right parameter, that's why d=(a,b); is evaluated as d=b.
  2. = has a higher precedence over the comma, so the expression c=a,b; is evaluated as (c=a),b;

Not part of the answer, but worth mentioning that the whole c=a,b; expression, is evaluated as b, not a, e.g. if you write d=(c=a,b); you get c=a AND d=b;

MByD
  • 135,866
  • 28
  • 264
  • 277
3

Consider the precedence of the C's comma operator.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
1

Take care to notice that the comma operator may be overloaded in C++. The actual behaviour may thus be very different from the one expected.

As an example, Boost.Spirit uses the comma operator quite cleverly to implement list initializers for symbol tables. Thus, it makes the following syntax possible and meaningful:

keywords = "and", "or", "not", "xor";

Notice that due to operator precedence, the code is (intentionally!) identical to

(((keywords = "and"), "or"), "not"), "xor";

That is, the first operator called is keywords.operator =("and") which returns a proxy object on which the remaining operator,s are invoked:

keywords.operator =("and").operator ,("or").operator ,("not").operator ,("xor");
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110