289

我注意到 Linux 内核代码使用 bool,但我认为 bool 是 C++ 类型。bool 是标准 C 扩展(例如 ISO C90)还是 GCC 扩展?

4

11 回答 11

399

bool存在于当前的 C - C99 中,但不存在于 C89/90 中。

在 C99 中,本机类型实际上被称为_Boolbool而是一个标准库宏定义在stdbool.h(预期解析为_Bool)。类型的对象_Bool持有 0 或 1,而truefalse也是来自stdbool.h.

请注意,顺便说一句,这意味着 C 预处理器将解释#if true#if 0除非stdbool.h包含在内。同时,C++ 预处理器需要本地识别true为语言文字。

于 2009-10-22T16:16:27.980 回答
128

C99 添加了内置_Bool数据类型(有关详细信息,请参阅Wikipedia),如果#include <stdbool.h>bool使用_Bool.

您特别询问了 Linux 内核。它假定存在并在include/linux/types.h_Bool中提供了booltypedef 本身。

于 2009-10-22T16:21:00.830 回答
33

C99 在stdbool.h中有它,但在 C90 中它必须定义为 typedef 或 enum:

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

bool f = FALSE;
if (f) { ... }

或者:

typedef enum { FALSE, TRUE } boolean;

boolean b = FALSE;
if (b) { ... }
于 2009-10-22T16:17:19.007 回答
31

不,boolISO C90 中没有。

这是标准 C(不是 C99)中的关键字列表:

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

这是一篇讨论内核和标准中使用的 C 的其他一些差异的文章:http: //www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

于 2009-10-22T16:12:42.840 回答
20
/* Many years ago, when the earth was still cooling, we used this: */

typedef enum
{
    false = ( 1 == 0 ),
    true = ( ! false )
} bool;

/* It has always worked for me. */
于 2013-08-21T20:28:59.683 回答
12

_Bool是 C99 中的关键字:它指定类型,就像intor一样double

6.5.2

2 声明为 _Bool 类型的对象大到足以存储值 0 和 1。

于 2009-10-22T16:19:22.987 回答
9

C99 定义了 bool,true并且falsestdbool.h.

于 2009-10-22T16:16:26.980 回答
3

stdbool.h定义宏truefalse,但请记住它们被定义为 1 和 0。

这就是为什么sizeof(true)equals sizeof(int),对于 32 位架构,它是 4。

于 2017-11-26T05:58:09.823 回答
2

stdbool.h是在 c99 中引入的

于 2009-10-22T16:16:29.920 回答
2

C99 添加了一种bool类型,其语义与之前在 C 中存在的几乎所有整数类型的语义完全不同,包括用于此类目的的用户定义和编译器扩展类型,并且某些程序可能具有“类型定义”到bool.

例如,给定bool a = 0.1, b=2, c=255, d=256;,C99bool类型会将所有四个对象设置为 1。如果使用 C89 程序typedef unsigned char bool,则对象将分别接收 0、1、255 和 0。如果使用char,则值可能如上,也c可能为 -1。如果它使用了编译器扩展bit__bit类型,则结果可能是 0、0、1、0(bit以等同于大小为 1 的无符号位字段或具有一个值位的无符号整数类型的方式处理)。

于 2018-11-09T17:25:18.747 回答
-1

没有这样的东西,可能只是一个 int 的宏

于 2009-10-22T16:13:50.627 回答