C99 中的_Bool类型(typedef'ed to boolin stdbool.h)没有标准定义的大小,但根据 C99 标准的第 6.2.5 节:
2 An object declared as type _Bool is large enough to store the values 0 and 1.
在 C 中,最小的可寻址对象(除了位域)是char,它至少有 8 位宽,并且sizeof(char)总是1.
_Bool因此bool具有sizeof至少1,并且在我见过的大多数实现中,sizeof(bool)/sizeof(_Bool)是1。
如果你看一下 GCC's stdbool.h,你会得到这个:
#define bool _Bool
#if __STDC_VERSION__ < 199901L && __GNUC__ < 3
typedef int _Bool;
#endif
#define false 0
#define true 1
所以如果在编译的时候使用老版本的GCC和老版本的C标准,你会使用int作为_Bool类型。
当然,作为一件有趣的事情,看看这个:
#include <stdio.h>
#include <stdbool.h>
int main() {
printf("%zu\n", sizeof(_Bool));
printf("%zu\n", sizeof(true));
printf("%zu\n", sizeof(false));
}
输出:
λ > ./a.out
1
4
4
GCC 4.2.4、Clang 3.0 和 GCC 4.7.0 都输出相同。正如 trinithis 指出的那样,sizeof(true)并sizeof(false)产生更大的尺寸,因为它们采用 int 文字的大小,至少是sizeof(int).