The _Bool
输入 C99 (typedef
'ed to bool
in 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
and bool
因此有一个sizeof
至少1
,并且在我见过的大多数实现中,sizeof(bool)
/ sizeof(_Bool)
is 1
.
如果你看一下 GCC 的stdbool.h
,你会得到这个:
#define bool _Bool
#if __STDC_VERSION__ < 199901L && __GNUC__ < 3
typedef int _Bool;
#endif
#define false 0
#define true 1
所以如果编译时使用旧版本的GCC和旧版本的C标准,你将使用int
as a _Bool
type.
当然,有趣的是,看看这个:
#include <stdio.h>
#include <stdbool.h>
int main() {
printf("%zu\n", sizeof(_Bool));
printf("%zu\n", sizeof(true));
printf("%zu\n", sizeof(false));
}
Output:
λ > ./a.out
1
4
4
GCC 4.2.4、Clang 3.0 和 GCC 4.7.0 的输出都相同。正如 Trinithis 指出的那样,sizeof(true)
and sizeof(false)
产生更大的尺寸,因为它们采用 int 文字的大小,这至少是sizeof(int)
.