0

can someone explain this ?

int main() { int i=0; cout<<(i=0?1:2?3:4); return 0; } // Output 3

10th May 2019, 3:40 PM
San Anemos
San Anemos - avatar
3 Respostas
10th May 2019, 5:22 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 1
i=0 is an assignment. Maybe i==0 was meant? i=0 returns 0, which evaluates as false. So for the first part of the chain, the result will be 2 (equalling if (i) 1; else 2;). 2 checked for true or false, since it is not 0, is true, so the final result will be 3. If you exchanged the 2 for a 0, the result would be 4.
10th May 2019, 4:44 PM
HonFu
HonFu - avatar
+ 1
As already said: the expression i=0 evaluates to 0, that evaluates to false. Then false ? 1 : 2 is 2. Therefore you have true ? 3 : 4 so you get 3. Remember: a) if(x) is same as if(x!=0) b) if(!x) is same as if(x==0) Parentheses and readable code are heavily underestimated!
10th May 2019, 6:24 PM
Daniel Adam
Daniel Adam - avatar