1

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();
}
Wusiji
  • 599
  • 1
  • 7
  • 24
  • 2
    You're looking for logical negation operator, and yes, the `int` will be converted to `bool`, just like in the `if`. – chris Nov 28 '14 at 03:10

3 Answers3

2

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.

Mukit09
  • 2,956
  • 3
  • 24
  • 44
1

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..

Amol Bavannavar
  • 2,062
  • 2
  • 15
  • 36
  • "Of course" is a bit weird because it might very well not be intuitive. Other languages prohibit conversions between integers and booleans. – chris Nov 28 '14 at 03:16
1

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

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252