0

When assigning a value to a bool, we have 2 options:

bool b = true;
bool b = 1;

Now my question is are these 2 any different in C++? And what's better to use?

The Coding Fox
  • 1,488
  • 1
  • 4
  • 18
  • 8
    Both are valid options supported by the standard. Using the value of `true` is unambiguous and clearer overall to the reader than the latter. – jrd1 Mar 31 '22 at 15:53
  • Actually, you can count on 0 (zero) being `false`. Any value that is **not zero** is `true`. – Thomas Matthews Mar 31 '22 at 16:20
  • `bool b = 1;` uses a conversion from `int` to `bool`; same as `bool b = 42;`. `bool b = true` uses the right type. – Pete Becker Mar 31 '22 at 16:21
  • If you assign any non-zero value to a `bool`, `bool b = 42`, for example, the conversion of integer to `bool` changes its value internally in the `bool` to 1. So after `bool b = 42`, the check `b == 1` will be true. As mentioned by @jrd1 using `true` and `false` as the values is the best, unambiguous approach. I personally don't like counting on the internal representation of `true`. In addition, instead of checking `if (b == true)` you can just use `if (b)` or instead of `if (b == false)` you can just use `if (! b)`. That shorter form is/can also be used to check for non-zero or zero value. – lurker Mar 31 '22 at 16:33
  • @lurker -- re: "changes its value internally in the `bool` to 1" -- no, it changes the value of the `bool` to `true`. There is no requirement that `true` be represented by 1, nor that `false` be represented by 0. When a `bool` value is converted to an integer value, `false` becomes 0 and `true` becomes 1. Yes, the check `b == 1` is true; also, `b == 42` is true; and `b == 0` is false. But that's because of conversions, not because of the internal representation. (yes, every implementation I know of uses 0 and 1, but that's an implementation detail, not a requirement) – Pete Becker Mar 31 '22 at 17:05
  • @PeteBecker I didn't express it correctly. Thank you for the correction. My primary point was that the behavior of `true` for a `bool` is as a 1 if compared or output as an `int` or even as `cout << boolValue`. When I had commented on a different question that the comparison `if (b == 1)` (where `b` is s `bool`) was "improper" to check for true, I was scolded by another C++ programmer and told that it was fine. However, I still don't think it's a good idea. – lurker Mar 31 '22 at 17:07
  • @lurker -- "don't think it's a good idea" -- I agree completely. – Pete Becker Mar 31 '22 at 17:13
  • There are many more options, like `bool b = 123;`, or `bool b = "false";`, or `bool b = 3.14;`, or ... – molbdnilo Mar 31 '22 at 17:36

0 Answers0