有点标题党了,准确的说是C语言标准中并无bool这个关键字来表示布尔类型。
在C++中我们通常使用bool变量存储逻辑值。
但是,C语言中是没有bool类型的,C语言中只有_Bool类型。
今天和人聊到这个问题,确实容易搞混淆,写出来记录一下。
[ISO/IEC 9899:2011(E) §7.18] Boolean type and values <stdbool.h>
The header <stdbool.h> defines four macros.The macro
boolexpands to_Bool.
The remaining three macros are suitable for use in#ifpreprocessing directives. They aretruewhich expands to the integer constant 1,falsewhich expands to the integer constant 0, and__bool_true_false_are_definedwhich expands to the integer constant 1.
Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.259)
[C Primer Plus 5th P46]_Bool类型由C99引入,用于表示布尔值,即C用值1表示true,用值0表示false,所以_Bool类型也是一种整数类型。只是原则上它们仅仅需要1位来进行存储。
因为对于0和1来说,1bit的存储空间已经够了。
C对真(true)的范围放的非常宽。所有非0的值都被认为是真,只有0被认为是假。这使得判断条件是建立在数值的基础上而不是在真/假的基础上。要谨记如果表达式为真,它的值就为1;如果为假,它的值就为0.因此很多表达式实际上是数值的。——C Primer Plus5th P123
C99提供了一个stdbool.h文件。包含这个头文件就可以使用bool来代替_Bool,并把true和false定义成值为1和0的符号常量。在程序中包含这个头文件可以写出与C++兼容的代码,因为C++把bool、true和false定义为关键字。——C Primer Plus 5th P125如果您的系统不支持
_Bool,则可以使用int来替代_Bool。——C Primer Plus 5th P125
以下代码用于测试:
1 | // 直接使用bool和flase是错误的 |
使用gcc编译(gcc -o testbool testbool.c)会产生如下错误:
1 | testbool.c: In function 'main': |
当我们包含stdbool.h之后久不会报错了。
1 |
编译(一定要添加std=c99)运行结果:
1 | x is false |
我们来看一下stdbool.h中的代码(Visual Studio2015中的):
1 | // stdbool.h |
下面这个版本是MinGW中的stdbool.h:
1 | /* Copyright (C) 1998-2015 Free Software Foundation, Inc. |
可以看出来,包含了stdbool.h之后使用的bool实际上也是_Bool类型的,而true和false也是被预处理器定义为了1和0的字面值常量,所以能够实现使用bool和true以及false关键字的目的,也算是曲线救国吧:)