我注意到Linux内核代码使用bool类型,但我以为bool类型是c++类型。bool是标准的C扩展名(例如,ISO C90)还是GCC扩展名?
当前回答
_Bool是C99中的关键字:它指定类型,就像int或double一样。
6.5.2 2声明为_Bool类型的对象 是否大到足以存储值0 和1。
其他回答
C99在stdbool.h中定义了bool, true和false。
C99在stdbol .h中有它,但在C90中必须定义为类型定义或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) { ... }
C99添加了一个内置的_Bool数据类型(详见维基百科),如果您#include <stdbool.h>,它将bool作为_Bool的宏提供。
您特别提到了Linux内核。它假定存在_Bool类型,并在include/linux/types.h中提供bool类型定义。
h定义了true和false宏,但是请记住它们被定义为1和0。
这就是sizeof(true) = sizeof(int)的原因,对于32位架构,sizeof(int)为4。
/* 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. */