14

Please explain the output of this program:

int main()
{    
    int a,b,c,d;  
    a=10;  
    b=20;  
    c=a,b;  
    d=(a,b);  
    printf("\nC= %d",c);  
    printf("\nD= %d",d);  
}

The output which I am getting is:

C= 10  
D= 20

My doubt is what does the "," operator do here?
I compiled and ran the program using Code Blocks.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Swamy
  • 285
  • 1
  • 4
  • 8
  • possible duplicate of [What does the comma operator \`,\` do in C?](http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c) – Mohit Jain Jul 09 '15 at 13:04

3 Answers3

24

The , operator evaluates a series of expressions and returns the value of the last.

c=a,b is the same as (c=a),b. That is why c is 10

c=(a,b) will assign the result of a,b, which is 20, to c.

As Mike points out in the comments, assignment (=) has higher precedence than comma

Eduardo
  • 8,362
  • 6
  • 38
  • 72
12

Well, this is about operator precedence:

c=a,b

is

equivalent to

(c=a),b

The point is, the "," operator will return the second value.

Thus

c=a,b

assigns a to c and returns b

d=(a,b) 

returns b and assigns it to d

Udo Klein
  • 6,784
  • 1
  • 36
  • 61
5

The comma operator evaluates all its operands, then yields the value of the last expression.