为什么布尔数据类型没有在 C 中实现 [英] Why was the boolean data type not implemented in C
问题描述
我的一个朋友问了一个问题,为什么C编程语言中没有Boolean
数据类型.我做了一些搜索和阅读.我在堆栈溢出中得到了几个问题和答案,
One of my friends asked a question, why is there no Boolean
data type in the C programming language. I did a bit of searching and reading. I got few questions and answers in stack overflow saying that,
- 所有数据类型都应该是可寻址的,一个位是不能寻址的.
- 主流CPU硬件层面的基本数据结构是字节.对这些 CPU 中的位进行操作需要额外的处理.
我们可以以这种方式使用布尔值
We can use a bool in this manner
#define bool int
#define TRUE 1
#define FALSE 0
或使用 typedef
s.
但我的问题是:为什么它没有在 C 中实现为数据类型,即使在这么多年之后.实现单字节数据类型来存储布尔值而不是显式使用 int
或 short
是否有意义.
But my question is this: why wasn't it implemented as a data type in C, even after so many years. doesn't it make sense to implement a one byte data type to store a boolean value rather than using int
or short
explicitly.
推荐答案
这不再是真的了.自 C99 起,内置的布尔类型,也就是 _Bool
可用.如果包含 stdbool.h
,则其别名 bool
也为你准备好了.
That's not true any more. The built-in boolean type, aka _Bool
is available since C99. If you include stdbool.h
, its alias bool
is also there for you.
_Bool
是真正的原生类型,而不是 int
的别名.至于它的大小,标准只规定它的大小足以存储0
和1
.但实际上,大多数编译器确实将其大小设为 1
:
_Bool
is a true native type, not an alias of int
. As for its size, the standard only specifies it's large enough to store 0
and 1
. But in practice, most compilers do make its size 1
:
例如,这个ideone上的代码片段输出1
:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool b = true;
printf("size of b: %zu
", sizeof(b));
return 0;
}
这篇关于为什么布尔数据类型没有在 C 中实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!