Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing bool values in C/C++

Tags:

c++

c99

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?

like image 889
fbafelipe Avatar asked Oct 05 '11 13:10

fbafelipe


3 Answers

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.

like image 52
David Schwartz Avatar answered Sep 28 '22 16:09

David Schwartz


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

like image 43
Martin Avatar answered Sep 28 '22 16:09

Martin


According to the standard:

  • true converts to 1
  • false converts to 0

And he cast to int is not necessary as the conversion to int is implicit.

like image 38
curiousguy Avatar answered Sep 28 '22 16:09

curiousguy