问题
From some reading on Stack Overflow, I gather that bool
, as defined in stdbool.h
, is a macro that expands to the built-in type _Bool
, and that true
is defined as 1
and false
is defined as 0
.
Is casting to bool
guaranteed to return a value of 0
or 1
? Might a _Bool
variable, including cast rvalues, ever attain a value other than 0 or 1?
The following code implies that _Bool
variables, including cast rvalues, will only have values of 0
or 1
, but I'd like to confirm that this is guaranteed, and that I'm not observing target- or compiler version-specific behavior.
(FWIW, I'm most specifically interested in confirming that only NULL
, cast to _Bool
, will be 0
, and that all other possible pointer values, cast to _Bool
, will be 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
回答1:
C 2018 6.3.1.2 1 says:
When any scalar value is converted to
_Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
回答2:
Yes, a cast to bool
is guaranteed to result in 0 or 1, up to the limit that undefined behavior can produce anything. If there's undefined behavior leading up to the path where conversion to bool
happens, it may so happen that you observe strange things, since the compiler may have rightfully made transformations based on assumptions that are no longer valid. For example, if the implementation performs the collapse to 0/1 at store time, it may assume when loading a bool
from memory that the value is already 0 or 1, and does not need further collapse. If the storage for the bool
object has been altered via a buffer overflow, aliasing violation, etc. then a different value might end up being seen.
来源:https://stackoverflow.com/questions/58886804/is-bool-cast-reliably-0-or-1