简体   繁体   English

在C ++中使用bool而不是char有什么意义?

[英]In C++ What's the point of using bool instead of char?

sizeof(char) and sizeof(bool) are both equal to 1 (in my compiler/system/whatever, I've heard that it's not always the same value), a bool can only store true or false while a char can take more values and can act as multiple bool variables using bitwise operators (8 bits, each bit can be used as 1 bool for a total of 8 bools) sizeof(char)和sizeof(bool)都等于1(在我的编译器/系统/无论如何,我听说它并不总是相同的值),bool只能存储true或false,而char可以更多值可以使用按位运算符作为多个bool变量(8位,每位可以用作1个bool,总共8个bool)

So is there any advantage on using bool instead of char? 那么使用bool而不是char有什么好处吗?

So aside from readability is there anything else? 除了可读性之外还有别的吗? I've read somewhere that int gets processed faster than short or byte even if takes more memory. 我已经读过某个地方,即使占用更多内存,int的处理速度也比short或byte快。 Is there any difference in terms of speed between char and bool? char和bool之间的速度有什么不同吗?

The main point of using bool is to express intent. 使用bool的主要目的是表达意图。 If a variable is intended to store a value with true/false semantics, allowing for additional values is just a potential source of errors. 如果变量旨在存储具有true / false语义的值,则允许其他值只是潜在的错误来源。

bool is an abbreviation of "boolean", so every one familiar with boolean algebra can be sure that the variable might store only one of the two logical values ( true or false ): if you're need a variable that could be in only one of these two logical states, is there a reason to use something that could store anything else? bool是“boolean”的缩写,所以每个熟悉布尔代数的人都可以确定变量可能只存储两个逻辑值中的一个( truefalse ):如果你需要一个只能在一个变量中的变量在这两种逻辑状态中,是否有理由使用能存储其他东西的东西?

The only size, clearly defined by the standard is sizeof(char) , it is 1 byte, but sizeof(bool) differs . 标准明确定义的唯一大小是sizeof(char) ,它是1个字节,但sizeof(bool) 不同 What about 1 bit per value, it's about boolean vector template. 每个值1位,它是关于布尔矢量模板的。

[taking an edit into attention] [引起注意的编辑]

You've profiled your application and found this to be a bottleneck? 您已经分析了您的应用程序并发现这是一个瓶颈? As I know, there's no advantages, except using boolean vectors if you're need to store and manipulate a couple of boolean variables. 据我所知,除了使用布尔向量,如果你需要存储和操作几个布尔变量,没有任何优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM