来自一些reading https://stackoverflow.com/questions/6627178/c99-why-are-false-and-true-defined-as-0-and-1-and-not-as-bool0-and-bool on https://stackoverflow.com/questions/21421061/need-for-bool-in-c99 堆栈溢出 https://stackoverflow.com/questions/49277769/why-is-c99s-bool-a-macro-rather-than-a-typedef,我推测bool
,如定义stdbool.h
, 是一个扩展为内置类型的宏_Bool
, 然后true
定义为1
and false
定义为0
.
正在投射到bool
保证返回值为0
or 1
?可能是_Bool
变量(包括强制转换右值)曾经获得过 0 或 1 以外的值吗?
下面的代码意味着_Bool
变量,包括强制转换右值,只会有以下值0
or 1
,但我想确认这是有保证的,并且我没有观察特定于目标或编译器版本的行为。
(FWIW,我最感兴趣的是确认只有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