Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c - Please Explain Comma Operator in this Program

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("
C= %d",c);  
    printf("
D= %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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...