从一些Stack Overflow的阅读资料,我了解到在stdbool.h中定义的
(顺便说一句,我最关心的是确认只有将
bool
是一个宏,它展开成内置类型_Bool
,而true
被定义为1
,false
被定义为0
。
强制转换为bool
是否保证返回值为0
或1
?_Bool
变量(包括转换后的rvalues)有可能达到除0
或1
之外的其他值吗?
下面的代码暗示_Bool
变量(包括转换后的rvalues)只会有0
或1
的值,但我想确认这是被保证的,并且我没有观察到特定于目标或编译器版本的行为。(顺便说一句,我最关心的是确认只有将
NULL
转换为_Bool
时才会是0
,将所有其他可能的指针值转换为_Bool
时都会是1
)$ cat ./main.c
#include <stdio.h>
#include <stdbool.h>
int main( int argc, char* argv )
{
int i;
int* p = &i;
int* n = NULL;
printf( "%zu\n", sizeof( (bool)p ) );
printf( "%p - %d\n", p, (bool)p );
printf( "%p - %d\n", n, (bool)n );
printf( "%d\n", (bool)3 );
return 0;
}
$ gcc --version
gcc (GCC) 8.2.1 20181215 (Red Hat 8.2.1-6)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc -g ./main.c && ./a.out
1
0x7ffdac3290bc - 1
(nil) - 0
1