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

匿名 (未验证) 提交于 2019-12-03 08:30:34

问题:

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?

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



回答2:

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



回答3:

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.



回答4:

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.



回答5:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!