Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:
int a = 2; bool b = a; int c = 3 + b; // 4 or 5?
Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:
int a = 2; bool b = a; int c = 3 + b; // 4 or 5?
Yes:
In C++ (§4.5/4):
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
In C, when a value is converted to _Bool
, it becomes 0 or 1 (§6.3.1.2/1):
When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
When converting to int
, it's pretty straight-forward. int
can hold 0 and 1, so there's no change in value (§6.3.1.3).
Is C/C++ .......
There's no language named C/C++.
bool type always guaranteed to be 0 or 1 when typecast'ed to int?
In C++ yes because section $4.5/4 says
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
.
int c = 3 + b;
// 4 or 5?
The value of c will be 4
Well, not always...
const int n = 100; bool b[n]; for (int i = 0; i < n; ++i) { int x = b[i]; if (x & ~1) { std::cout << x << ' '; } }
Output on my system:
28 255 34 148 92 192 119 46 165 192 119 232 26 195 119 44 255 34 96 157 192 119 8 47 78 192 119 41 78 192 119 8 250 64 2 194 205 146 124 192 73 64 4 255 34 56 2 55 34 224 255 34 148 92 192 119 80 40 190 119 255 255 255 255 41 78 192 119 66 7 8 192 119 192 73 64 240 255 34 25 74 64 192 73 64
The reason for this apparently weird output is laid out in the standard, 3.9.1 §6:
Values of type
bool
are eithertrue
orfalse
. Using abool
value in ways described by this International Standard as "undefined", such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neithertrue
norfalse
.
One more example when you are out of the safe boat:
bool b = false; *(reinterpret_cast(&b)) = 0xFF; int from_bool = b; cout << from_bool << " is " << (b ? "true" : "false"); *>
Output (g++ (GCC) 4.4.7):
255 is true
To be added to the FredOverflow's example.
There is no bool type in C pre C99 (Such as C90), however the bool type in C99/C++ is always guaranteed to be 0 or 1.
In C, all boolean operation are guaranteed to return either 0 or 1, whether the bool type is defined or not.
So a && b
or !a
or a || b
will always return 0 or 1 in C or C++ regardless of the type of a
and b
.