Alex Rivera | Logout

Is bool guaranteed to be 0 or 1 when converted to int?

Asked 2010-11-25T10:52:35.133
60

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?
Edit
Report

2 Answers

20

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.

answered 2010-11-25T11:02:40.970
10

One more example when you are out of the safe boat:

  bool b = false;
  *(reinterpret_cast<char*>(&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.

answered 2013-04-23T17:24:47.670

Your Answer