在C99标准之前,只能自定义bool量,常见的方式就是定义宏和枚举,例如:
① 枚举法
typedef enum bool = { False, Ture }
② 定义宏
typedef int BOOL ;
#define true 1
#define false 0
int main()
{
BOOL a = true;
BOOL b = false;
}
如上所示,BOOL量是通过int型进行定义,那sizeof(BOOL)结果就是4。
在C99中,引入了bool量,bool量通过char型定义存放在头文件stdbool中,stdbool如下:
#ifndef _STDBOOL_H #define _STDBOOL_H #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #else #define _Bool bool #if __cplusplus < 201103L #define bool bool #define false false #define true true #endif #endif #define __bool_true_false_are_defined 1 #endif
编译器不同,非0值不同,GCC编译时默认非0为1。
#include#include int main(void) { printf("sizeof(bool):%dn",sizeof(bool)); printf("%dn",true); printf("%dn",false); return 0; }
编译结果为:



