c – 为什么bool变量不能设置为0,除了直接赋值0?
发布时间:2020-12-16 10:31:03 所属栏目:百科 来源:网络整理
导读:我不能溢出bool变量变为零. bool类型的变量是1个字节长,所以我认为当变量存储256时它会溢出,但它不像我预期的那样. #includeiostreamint main(){ bool b = 0; std::cout sizeof(b) std::endl; // the result is 1 byte std::cout b std::endl; // the result
我不能溢出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.这两种类型的大小和布局都无关紧要.
如果你想要它在Standardese:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |