0

Coul someone explain this code to me? I don't understand why the output is 3.

i=0; cout<<(i=0 ? 1: 2 ? 3 : 4); return 0;

12th Jun 2019, 7:09 AM
Miosotis
4 Réponses
+ 7
a ? b : c; means: if a is true, return/evaluate b, otherwise return/evaluate c. i = 0 sets i to 0 and returns 0 (false) (note that you're not using == for comparison, but = for assignment). So in the expression i = 0 ? 1 : 2, the second branch (2) is evaluated. You end up with 2 ? 3 : 4. 2 evaluates to true, that's why 3 is returned.
12th Jun 2019, 7:15 AM
Anna
Anna - avatar
+ 2
Every integer that is not 0 evaluates to true. 0 = false, everything else = true
13th Jun 2019, 2:16 PM
Anna
Anna - avatar
+ 2
clear doubt. Thank you
14th Jun 2019, 5:55 AM
Miosotis
+ 1
Thanks Anna, but why 2 does it evaluate as true?
13th Jun 2019, 1:39 PM
Miosotis