1

I've seen code where a condition is evaluated based on an int variable instead of bool.

int condition
cin >> condition;
if (!condition)
    //do something 

I know that C++ supports that 0 is false and 1 is true, but is this safe code? Is it supported by all C++ compilers as a standard?

Could it also be a bad practice considering that you might switch to another language and find out that this kind of code isn't supported?

I mean, is it good practice at all?

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Floella
  • 1,279
  • 1
  • 22
  • 41
  • The "good practice" part is either opinion based or too broad, the on-topic part is covered in the dupe. – Baum mit Augen Nov 17 '15 at 12:23
  • *"I mean, is it good practice at all?"* - the answer is opinion-based, however, I'd prefer not to interpret `int` as `bool` since it often leads to unpredictable mistakes. – awesoon Nov 17 '15 at 12:25

1 Answers1

3

Yes it is safe to make that assumption. The standard defines the implicit conversion of various primitives to bool, and all the numeric types basically state that 0 converts to false and any non-zero value converts to true.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Yet IMHO it would be better to use `if(condition == 0)` to directly see what is going on. – Simon Kraemer Nov 17 '15 at 12:23
  • Just a side note: in MS's VB6 `true` is explicitly defined as `-1` `(0xFFFFFFFF)`. (just saying because it can be tedious tricky if you have to do some interopping) – Stefan Nov 17 '15 at 12:23
  • 1
    @Stefan And this is of relevance for this `C++` question how? – Simon Kraemer Nov 17 '15 at 12:24
  • 2
    @SimonKraemer: as stated; if you want your C++ assembly to communicate with the VB6 runtime it's relevant. Of course in a lot of circumstances this is not the case but I found it worth to mention that not every party will comply to the `0 = false; else = true` implementation. (triggerd by the `is this safe` part) – Stefan Nov 17 '15 at 12:29
  • 2
    @Stefan I undertsand what you are saying but not why. The question is about pure `C++` without stating neither `VB` nor anything about interoperability. In my opinion this is a pretty special case you are referring to, and your comment is somehow offtopic. BTW: Your comment contains an error. In `VB6` a `Boolean` value is 2 bytes in size and not 4. – Simon Kraemer Nov 17 '15 at 13:10