You are invited to Log in or Register a free Frihost Account!

# Is true bool always converted to 1?

Hello! I want to know if it's guaranteed that a bool that is true always converts into 1 when cast to an int, in C++.
Example:
 Code: int i = 20;    bool b = i;    cout << i + b << endl;

So can I be sure that the result always will be 21 in this case regardless which compiler?

I'm a bit worried that b might actually get the value 20. Should I stop worrying?
Fire Boar
Boolean is always stored as a single bit. 0 is off, 1 is on. When typecasted to any integer... let's take char as an example. It just adds zeros until it's the right length. So bool "true" to char is 1, plus 0000000 as padding making 0000001. In decimal, that's 1.

So... yes. Bool true does cast to 1, always.
AftershockVibe
I'm afraid fireboar is not entirely correct. Boolean values on any language are stored as a word (32 bits on your average 32bit machine) because that is the smallest unit the processor can work with.

While in C++ the standard is to convert true to 1 (although I'm not sure if it's de facto or specified), this is not the only value which represents true. Any value other than 0 can represent true.

In C (from which C++ is obviously derived), true was often represented as -1 as well (NOT operator on integer 0 gives -1 in twos complement notation).

In short, you're probably safe using it unless you have some bizarre or ancient compiler. You could always cast it yourself to make sure. Doesn't that code give you a warning anyway? If not, you're almost certainly safe.
ThePolemistis
Hello! I want to know if it's guaranteed that a bool that is true always converts into 1 when cast to an int, in C++.
Example:
 Code: int i = 20;    bool b = i;    cout << i + b << endl;

So can I be sure that the result always will be 21 in this case regardless which compiler?

I'm a bit worried that b might actually get the value 20. Should I stop worrying?

Basically 0 will always be false.
Anything else is true.
jeremyp
Hello! I want to know if it's guaranteed that a bool that is true always converts into 1 when cast to an int, in C++.
Example:
 Code: int i = 20;    bool b = i;    cout << i + b << endl;

So can I be sure that the result always will be 21 in this case regardless which compiler?

I'm a bit worried that b might actually get the value 20. Should I stop worrying?

You should worry because that's a really bad piece of code. Booleans are not integers and vice versa. You should not be trying to add the one to the other directly. The fact that you can is an unfortunate historical problem with the C-like languages (excepting modern ones like Java and C#).

Your whole question goes away if you use type correct operations e.g:

 Code: int i = 20;    bool b = i != 0;    cout << i + (b ? 1 : 0) << endl;

The internal implementation of type bool is not important in the above code, it'll always work.