Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsafe mix of xxx and bool in operation warning only when comparing value to TRUE

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 TRUEcomparision. 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?

like image 298
vlad_tepesch Avatar asked Feb 12 '23 19:02

vlad_tepesch


1 Answers

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.

like image 100
Klas Lindbäck Avatar answered Feb 14 '23 10:02

Klas Lindbäck