Never use a _Bool
(or bool
defined by #include <stdbool.h>
) if it is possible for the object to contain a value other than 0 or 1. The compiler is at liberty to assume the object will contain a value of 0 or 1 and produce unexpected results if it contains a different value. In particular, GCC tends to produce unexpected results from the following program:
foo.c
#include <stdio.h>
#include <string.h>
int main(void)
{
_Bool b;
memset(&b, 0xff, sizeof b);
printf("int = %d\n", (int)b);
printf("int_bool = %d\n", (int)(_Bool)b);
printf("int_bool_int = %d\n", (int)(_Bool)(int)b);
printf("int_not_not = %d\n", (int)!!b);
printf("not_not_int = %d\n", !!(int)b);
return 0;
}
On Debian GNU/Linux 11 x86_64:
$ gcc --version
gcc (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 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 -O2 foo.c -o foo
$ ./foo
int = 255
int_bool = 255
int_bool_int = 255
int_not_not = 255
not_not_int = 255
One might have expected most of those printed values to be 1 rather than 255.