我不能溢出 bool 变量变为零。 bool类型的变量是1个字节长,所以我认为当变量存储256时它会溢出,但它不是我预期的那样。
#include<iostream>
int main()
{
bool b = 0;
std::cout << sizeof(b) << std::endl; // the result is 1 byte
std::cout << b << std::endl; // the result is 0
b = 256;
std::cout << b << std::endl; // the result is 1,rather than the desired zero
return 0;
}
可能我没说清楚,只有1个字节时,0和256都存储为00000000(二进制)
最佳答案
将数字类型转换为 bool
的规则很简单:零变为 false
,所有其他值变为 true
。两种类型的大小和布局都无关紧要。
如果你想用标准语:
C++11 4.12: A zero value, null pointer value, or null member pointer value is converted to
false
; any other value is converted totrue
.
关于c++ - 为什么bool变量不能设置为0,除了直接赋0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498057/