0

Output of C++ code

Can someone explain this code and its output? https://code.sololearn.com/cBQue7W2Pihg/#cpp

24th Sep 2020, 8:55 PM
Edward Finkelstein
Edward Finkelstein - avatar
3 odpowiedzi
+ 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;
24th Sep 2020, 10:53 PM
Kevin ★
+ 2
You are very welcome
24th Sep 2020, 11:10 PM
Kevin ★
+ 1
Yes, this makes perfect sense, thank you, Kevin!
24th Sep 2020, 11:04 PM
Edward Finkelstein
Edward Finkelstein - avatar