Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please Explain Comma Operator in this Program

Tags:

c

comma

Please explain me 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.

like image 947
Swamy Avatar asked Feb 16 '13 14:02

Swamy


2 Answers

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

like image 161
Eduardo Avatar answered Sep 22 '22 03:09

Eduardo


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

like image 29
Udo Klein Avatar answered Sep 23 '22 03:09

Udo Klein