为什么布尔数据类型不是在C实现的 [英] Why was the boolean data type not implemented in C

查看:163
本文介绍了为什么布尔数据类型不是在C实现的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友问一个问题,为什么会出现在C编程语言没有布尔数据类型。我做了一些搜索和阅读。我在堆栈溢出一些问题和答案说,

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,


  1. 所有的数据类型应该是可寻址的,有点无法得到解决。

  2. 在主流CPU的硬件水平的基本数据结构是一个字节。操作上在这些CPU位需要额外的处理。

我们可以使用这种方式的一个bool

We can use a bool in this manner

#define bool int
#define TRUE 1
#define FALSE 0

或使用的typedef 秒。

不过,我的问题是:为什么不是实现为在C中的数据类型,即使过了这么多年。没有有意义实现一个字节的数据类型来存储一个布尔值,而不是使用 INT 明确。

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.

推荐答案

这是不正确的了。内置的布尔类型,又名 _Bool 是因为 C99使用 。如果包括 stdbool.h ,它的别名布尔也有你。

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 输出这个 code段 1

For example, this code snippet on ideone outputs 1:

#include <stdio.h>
#include <stdbool.h>
int main(void) {
    bool b = true;
    printf("size of b: %zu\n", sizeof(b));
    return 0;
}

这篇关于为什么布尔数据类型不是在C实现的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆