0
Output of C++ code
Can someone explain this code and its output? https://code.sololearn.com/cBQue7W2Pihg/#cpp
3 Answers
+ 4
i=0?1:2?3:4
The assignment operator( = ) has lower precedente than ternary operator( ? : ) so above code can be interpreted this way:
i = (0?1:2?3:4)
Ternary operators are the inline form of "if else" statements and have this shape:
( condition ? evaluateThisIfTrue : evaluateThisIfFalse)
0 is false according to boolean logic so (1) is ignored and we jump directly to the 2?3:4 part.
2 is truthy so we ignore that 4 and 3 is the value of the complete expression and we can replace it:
cout << i = (3);
"i" is now 3 and that value is logged because the assignment operator returns the value on its right hand.
I hope this makes sense.
The code could be mentally read this way:
if(0){ //false
i = 1;
}
else if(2){ //true
i = 3;
}
else { //never reached
i = 4;
}
cout << i;
+ 2
You are very welcome
+ 1
Yes, this makes perfect sense, thank you, Kevin!