c++ - C/C++ 中的 bool 是什么?关键字还是宏?

标签 c++ c boolean keyword

我提到了 this question ,其中一些答案表明 bool是整型(IDE 也将其视为关键字)。

但是,没有一个答案暗示 cplusplus 中提供的信息,这表示 bool是通过<cstdbool>添加的宏(在这种情况下,编译器可能会在编译时隐式添加此 header 以允许 bool )。这是 <stdbool.h> 的 g++ 版本.

那么bool到底是什么?是?整型关键字还是宏?

最佳答案

在 C 中,bool 是一个宏。

C 中没有名为bool 的内置类型或关键字,因此典型的实现使用标准库来#define truefalse 分别为 10if 语句的规则是根据“零”和“非零”表达式定义的,因此依赖于 true:

[C99: 6.8.4.1/2]: In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.

为了方便,C99增加了内置的中间类型_Bool,这种语言的实现一般是#definebool _ boolean 。这种类型是这样定义的:

[C99: 6.2.5/2]: An object declared as type _Bool is large enough to store the values 0 and 1.

这允许与 C++ 程序更好地兼容,其中可能包括使用 bool 类型的函数声明;不过,实际上,#define _Bool int 可能就足够了。


在C++中,bool既是内置类型又是关键字。

您提供的链接并未说明 bool 是 C++ 中的宏。它说:

The purpose in C of this header is to add a bool type and the true and false values as macro definitions.

In C++, which supports those directly, the header simply contains a macro that can be used to check if the type is supported.

这是正确的。

在语义上(即,就代码的“含义”而言),[C++11: 3.9.1/2] 定义了 bool 作为 C++ 中的整数类型。

词法(即,在代码中的“外观”方面),[C++11: 2.12/1] 将其列为关键字。事实上,作为整型名称一部分的所有标记也是关键字,包括(但不限于):

  • int
  • 未签名
  • boolean
  • 签名

但是,它从不在 C++ 中是宏。相反,您会得到一个宏 __bool_true_false_are_defined,您可以在多语言代码中使用它来根据您使用的是 C 还是 C++ 来切换对 bool 的处理;请注意,我不确定我能想到一个有用的示例。

关于c++ - C/C++ 中的 bool 是什么?关键字还是宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18042223/

相关文章:

c - 十六进制数加一个字节

return 语句中的 Java 逻辑运算符

c# - 检查四个 boolean 变量是否具有相等的值,非显而易见?

c++ - QT Creator,c++11 的语法检查

c++ - 多幅图像实时SIFT描述符匹配C++/OpenCV

在函数中更改指针地址

c++ - 如何使用 NCurses 阻止 C++ 中的某些键

c++ - 如何使用 WinDbg 分析 VC++ 应用程序的故障转储?

c++ - 搜索 map 和打印 vector

c - 数组长度问题