Search code examples
cbooleanstdbool

Is (bool) cast reliably 0 or 1?


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

Solution

  • 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.