I have a library that is implemented in C (C89 compatible). It defines a bool data type bool32
. It also defines the boolean literals TRUE
and FALSE
:
#ifndef TRUE
# define TRUE (0 == 0)
#endif
#ifndef FALSE
# define FALSE (0 != 0)
#endif
typedef uint32_t bool32;
C code like the following compiles without warning:
bool32 h = TRUE;
if(h==TRUE){
}
if(h==FALSE){
}
the same code in a cpp compiles with the following warning:
1>[filename/line): warning C4805: '==' : unsafe mix of type 'bool32' and type 'bool' in operation
But only for the TRUE
comparision. the FALSE
comparison does not produces a warning.
I also checked the preprocessed files to ensure that the above definition of TRUE
and FALSE
is used and not another one. This look ok.
Does anybody have an explanation why the warning occurs only on TRUE
and how to avoid this warning? And another Question: Why does the Compiler in C-Mode does not warn?
You get the warning because comparing an integer to a bool
is bug-prone.
Consider the following:
bool32 x = 3;
if (x == FALSE) {
printf("x is false\n");
}
else if (x == TRUE) {
printf("x is true\n");
}
else {
printf("x is neither true nor false!\n");
}
Output:
x is neither true nor false!
Note that this is a problem regardless whether TRUE/FALSE are integer or bool, it's just that the compiler cannot correctly detect it when TRUE is an integer.
The problem exists because there are several integer values that are considered true. There is only one value that is considered false, 0
, so there can be no mixup there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With