c++ - Confusing outcome of C conditional operator -
int a=1,b=2,c=3; int x=1; int y=10; = x ? b : c; cout<< a; // outputs 2 (the value of b) = y ? b : c; cout<< a; // outputs 2 (the value of b) now, @ following.
a=0; x=0; = x ? b : c; cout<< a; // outputs 3 (the value of c !!!!) why unusual behaviour ?? when , x both 0, expression evaluates false , otherwise, true. please explain.
because x 0.
recall ternary operator, if written condition ? : b returns a if condition true , b otherwise. using numbers, , number except 0 considered true boolean.
x ? b : c in case 0 ? 2 : 3, , since 0 false, evaluates 3. 3 gets assigned a variable , printed - nothing unusual going on here.
Comments
Post a Comment