fbafelipe
fbafelipe

Reputation: 4952

Summing bool values in C/C++

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?

Upvotes: 8

Views: 10098

Answers (4)

Quantumboredom
Quantumboredom

Reputation: 1466

David Schwartz 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 compares equal to 0; otherwise, the result is 1.

Since 6.3.1.1 of the standard also makes it clear that _Bool is subject to integer promotions it's clear that a _Bool will always be either 0 or 1.

Upvotes: 1

curiousguy
curiousguy

Reputation: 8268

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.

Upvotes: 1

Martin
Martin

Reputation: 292

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

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182789

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.

Upvotes: 12

Related Questions