Summing bool values โ€‹โ€‹in C / C ++

Consider the following C ++ code:

bool a = 5; bool b = 6; int c = (int)a + (int)b; 

When I compile and run this code, c is 2. The standard ensures that in any compiler / platform, the bool values โ€‹โ€‹initialized with false (0) or true (not necessarily 1) will be 1 in operations and the code above will always result to the fact that c will be 2?

Does C99, including stdbool.h, still work?

+6
source share
4 answers

Section 4.7 (integer versions) of the C ++ standard states:

If the source type is bool, false is converted to zero and true is converted to one.

Section 4.9 makes the same floating point conversion guarantee.

+10
source

For compilers, a rule often indicates that false is 0, and everything else will be true. However, calling bool as an integer type is usually considered bad. The standard, however, includes a rule for converting to int, and your assumption is true false = 0 and true = 1, as long as the compiler adheres to the standard!

Anyway, why arithmetic with bool types?

Hope for this help

+1
source

In accordance with the standard:

  • true converts to 1
  • false converts to 0

And it discards the int not necessarily, because the conversion to int implicit.

+1
source

David Schwartz has already answered for C ++. For the C99 standard, we have 6.3.1.4:

When any scalar value is converted to _Bool, the result is 0 if the value is compared to 0; otherwise, the result is 1.

Since 6.3.1.1 of the standard also makes it clear that _Bool is exposed to integer shares, it is clear that _Bool will always be either 0 or 1.

+1
source

Source: https://habr.com/ru/post/898669/


All Articles