Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int?

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?

Solution 1:

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).

Solution 2:

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 either true or false. Using a bool 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 neither true nor false.