Reputation: 69
What is bool guaranteed to return as? Can I rely on a bool type to always be interpreted as 0 or 1? If bool's numerical interpretation isn't reliable in C99 is there a standard where it is? Are there any things I should look out for in LLVM, GCC, or Visual C++ when relying on bool for arithmetic?
Just for example what if I did this:
// An example of calculating a possible stride in bytes.
// hasData(), is8bit(), and is16bit() return as bool type
unsigned int stride = object->hasData() * object->size() *
(object->is8bit() * sizeof(uint8_t) +
object->is16bit() * sizeof(uint16_t));
In the example I'm betting on bool type only returning 0 or 1.
Upvotes: 2
Views: 323
Reputation: 106052
Boolean value of an expression is either 1
(true
) or 0
(false
) always and are of type int
instead of _Bool
.
- The header
<stdbool.h>
defines four macros.- The macro
bool
expands to_Bool
.- The remaining three macros are suitable for use in
#if
preprocessing directives. They are
true
: which expands to the integer constant1
,false
: which expands to the integer constant0
, and- __bool_true_false_are_defined which expands to the integer constant 1.
Upvotes: 1
Reputation: 129374
The C99 standard requires the compiler to produce _Bool
values that are either 0 or 1. C++ also has this requirement. No, I don't know the exact page of the standard document that describes this.
Of course, 16 years after the introduction, it's still possible that there are bugs in compilers, and more so if we have a compiler that is, say, 10 years old and wasn't well tested for C99 compatibility when it was produced. But I frequently write code that relies on the compiler producing 0 or 1 from conditional expressions, for example.
Upvotes: 1
Reputation: 28997
In C++ bool
is a type which is guaranteed to contain either true
or false
. When converted to int
(as in your example), these correspond to 1 and 0 respectively.
Upvotes: 1
Reputation: 145879
What is bool guaranteed to return as? Can I rely on a bool type to always be interpreted as 0 or 1?
In a strictly conforming program a _Bool
(or bool
from stdbool.h
) expression is guaranteed to be evaluated to either 0
or 1
.
If you get a different value from a bool
expression it means you are invoking some undefined behavior upstream.
Upvotes: 5