Consider the C++ code below:
bool a = 5;
bool b = 6;
int c = (int)a + (int)b;
When I compile&run this code, c has the value 2. Does the standard guarantee that, in any compiler/platform, bool values initialized with false (0) or true (not necessarily 1) will be 1 in operations and the code above will always result in c being 2?
And in C99, including stdbool.h, is that still valid?
Section 4.7 (integer versions) of the C++ standard says:
If the source type is bool, the value false is converted to zero and the value true is converted to one.
Section 4.9 makes the same guarantee for floating point conversions.
For compilers, the rule is often that false is 0 and anything else will be true. However, treating bool like it is an integer type is usually considered bad form. The standard however include a rule to convert to int and you assumption is correct false = 0 and true = 1 as long as the compiler adhere to the standard!
In any case, why arithmetic with bool types?
Hope this help
According to the standard:
true
converts to 1false
converts to 0And he cast to int
is not necessary as the conversion to int
is implicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With