许多编译器似乎只保留bool值中的0或1,但我不确定这将始终有效:
int a = 2;
bool b = a;
int c = 3 + b; // 4 or 5?
Run Code Online (Sandbox Code Playgroud)
Mat*_*hen 48
是:
在C++(§4.5/ 4)中:
bool类型的rvalue可以转换为int类型的rvalue,false变为零,true变为1.
在C中,当一个值转换为_Bool,它变为0或1(§6.3.1.2/ 1):
当任何标量值转换为_Bool时,如果值比较等于0,则结果为0; 否则,结果为1.
转换到时int,它非常简单. int可以保持0和1,因此值没有变化(§6.3.1.3).
fre*_*low 19
好吧,并不总是 ......
const int n = 100;
bool b[n];
for (int i = 0; i < n; ++i)
{
int x = b[i];
if (x & ~1)
{
std::cout << x << ' ';
}
}
Run Code Online (Sandbox Code Playgroud)
我的系统输出:
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
Run Code Online (Sandbox Code Playgroud)
这个看似奇怪的输出的原因在标准3.9.1§6中列出:
类型的值
bool是true或false.使用bool本国际标准描述的方式中的值为"未定义",例如通过检查未初始化的自动对象的值,可能会使其表现为既不是也不true是false.
Pra*_*rav 17
是C/C++ .......
没有名为C/C++的语言.
在类型转换为int时,bool类型总是保证为0或1?
在C++中是的,因为$ 4.5/4节说
bool类型的rvalue可以转换为int类型的rvalue,false变为零,true变为1.
.
int c = 3 + b;// 4或5?
c的值为4
当你离开安全船时还有一个例子:
bool b = false;
*(reinterpret_cast<char*>(&b)) = 0xFF;
int from_bool = b;
cout << from_bool << " is " << (b ? "true" : "false");
Run Code Online (Sandbox Code Playgroud)
输出(g ++(GCC)4.4.7):
255 is true
Run Code Online (Sandbox Code Playgroud)
要添加到FredOverflow的示例中.