关于BOOL与bool

来源:互联网 发布:日本科技振兴机构知乎 编辑:程序博客网 时间:2024/05/20 14:19

关于BOOL和bool,最基本的描述:

1.类型不同,bool是布尔型,而BOOL就是int型;

2.长度不同,bool是一个字节,而BOOL是int的长度;

3.取值不同,bool只有true和false,而BOOL理论上就可以取所有int值,但是既然是BOOL就单独给宏定义了两个值TRUE(1),FALSE(0),但在Win32 API中很多返回值为BOOL的函数都是三值逻辑(TRUE/FALSE/ERROR,返回值为大于0的整数时为TRUE,返回值为0时候,为FALSE,返回值为-1时为ERROR。)。

--------------------------------------------------------------------------------------------------------------------------------------

关于BOOL的进一步描述:

BOOL是在windef.h宏定义的,具体如下:

/* windef.h */typedef int                 BOOL;

但是,在VC6.0环境下(尽管VC6.0落伍了,但有时也要使用),如果直接包含这头文件就会出现莫名其妙的错误,具体测试程序如下:

#include <stdio.h>//#include <windows.h>#include <windef.h>int main(){BOOL flag = TRUE;printf("%d\n", flag);return 0;}

编译不通过,提示如下:

Compiling...
test.c
d:\software\microsoft visual studio\vc98\include\winnt.h(3143) : error C2061: syntax error : identifier 'PCONTEXT'
d:\software\microsoft visual studio\vc98\include\winnt.h(3144) : error C2059: syntax error : '}'
Error executing cl.exe.

如果你真心想用BOOL,真心想用微软的头文件,那就直接包含windows.h这个头文件就行了。但是个人建议,实际上不如自己宏定义,使用BOOL无非是想让程序易读而已,反正实际上也是个int,不如自己宏定义了,免得去包含那些头文件:

#ifndef FALSE#define FALSE 0#endif
#ifndef TRUE#define TRUE 1#endif
--------------------------------------------------------------------------------------------------------------------------------------

关于bool的进一步描述:

bool实际上C++中的类型,C语言中原本没有bool类型,但C99标准中stdbool.h定义了一个_Bool的宏。所以可以说在C和C++中,bool也是不同的类型,C++中是布尔型,而C中是int。

/*stdbool.h -- Boolean type and values(substitute for missing C99 standard header)public-domain implementation from [EMAIL PROTECTED]implements subclause 7.16 of ISO/IEC 9899:1999 (E)*/#ifndef __bool_true_false_are_defined#define __bool_true_false_are_defined 1/* program is allowed to contain its own definitions, so ... */#undef bool#undef true#undef false#if __STDC_VERSION__ < 199901typedef int _Bool#endif#define bool _Bool#define true 1#define false 0#endif /* !defined(__bool_true_false_are_defined) */