Explain it | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Explain it

int i; i=1,2,3; printf("i=%d",i);

19th Mar 2020, 9:46 AM
Md Raziullah Khan
Md Raziullah Khan - avatar
7 Answers
+ 3
Comma operator evalutes left hand operand and discards its result. Then it evaluates second operand and returns its value. So result is 1. //not 3 , See next answer. https://en.m.wikipedia.org/wiki/Comma_operator
19th Mar 2020, 9:53 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
Result is 1
19th Mar 2020, 9:59 AM
Md Raziullah Khan
Md Raziullah Khan - avatar
+ 2
Md Raziullah Khan , Can you try to understand second code by yourself? I can answer , but in order to learn C you should be able to think about such things by yourself. It's not hard. At least try it once. Try to answer second question. If you feel difficulty at any point you are welcome to ask.
19th Mar 2020, 10:41 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Md Raziullah Khan , Thanks for pointing that out. 🤪 Here's explanation why is it so: Comma operator has least precedence among all the operators available in C. So i is assigned value 1 and then comma operator discards 1. In order to evaluate rhs of expression before assignment we can use parantheses. i = (1,2,3); //now i will be 3
19th Mar 2020, 10:11 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
And int a=14,b=12,c; c=a>b?1,2,3:4,5,6; printf("c=%d",c);
19th Mar 2020, 10:33 AM
Md Raziullah Khan
Md Raziullah Khan - avatar
+ 1
Answer is 3
19th Mar 2020, 10:33 AM
Md Raziullah Khan
Md Raziullah Khan - avatar
0
It's just assignment operator has higher precedence than comma operator so that's just assigning i to 1.
21st Mar 2020, 7:43 AM
Hima
Hima - avatar