0
can someone explain this ?
int main() { int i=0; cout<<(i=0?1:2?3:4); return 0; } // Output 3
3 Respostas
+ 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.
+ 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!