Reputation: 6883
I have a library that is implemented in C (C89-compatible). It defines a Boolean 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.
Is there an explanation why the warning occurs only on TRUE
and how to avoid this warning? And another question: Why does the compiler not warn in C mode?
Upvotes: 6
Views: 7531
Reputation: 33273
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 Boolean. 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't be any mix up there.
Upvotes: 9