So in c++, 1 is equalavent to true
int test = 1;
if(test) {// returns true; enter if loop
passgo();
collect200dollars();
}
Does the flip operator (sorry for lack of better name) work on this?
int test = 1;
if(!test) {// returns false; do not enter if loop
...
}else{
goToJail();
}
Not only one but also all non zero values are equivalent to true. When you are writing
if(test)
it means, compiler checks if the value of test is equivalent to 0 or not. If value of test is equivalent to 0, then the if expression returns false, otherwise returns true.
Yes, you can check it also for false... It will negate test which is true because it is not a zero. In conversion of int to bool, If the value is not a zero then it will consider it as true otherwise it is false. In your case you assigned test = 1 that means true, and you are negating true value means if condition will directly go to execute else code..
Any fundamental numerical type ( int
, double
, float
etc) different from zero will be converted to a bool
equal to true
in a condition. So the !
operator will negate a bool
which is true
, and the latter will become false
.
See related https://stackoverflow.com/a/8591324/3093378
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.