I have following code:
typedef enum
{
FOO,
BAR,
BAZ
} foo_t;
static void afunc(bool is_it_on)
{
/* Do the job */
}
int main(void)
{
afunc(BAZ);
return 0;
}
Compiling this code does not generate any warning message, even with the -Wall -Wextra options given to the compiler. I have even tried with -Wconversion option, which didn't take any effect, because bool and enum seemed to be of same size for g++ (the size of enum type is not defined in specification as far as I know).
I have combed through the GCC manual and found nothing about it.
Questions:
- Is there a way to force the compiler to generate a warning in cases like this?
- Or is it that this implicit casting is legal by c++ specification?
Compiler that I am using: GCC 4.1.2 (2007-02-13)
Conclusion:
The only viable solution to this seems to define a new type to represent 0 or 1, and use it instead of bool.
The code would be like following, and g++ complains about type conversion:
typedef enum
{
FOO1,
FOO2
} foo_t;
typedef enum
{
MY_FALSE,
MY_TRUE
} my_bool_t;
void foo(my_bool_t a)
{
}
int main(void)
{
/*
* GCC generates an error.
* error: cannot convert ‘foo_t’ to ‘my_bool_t’
* for argument ‘1’ to ‘void foo(my_bool_t)’
*/
foo(FOO1);
return 0;
}
--std=c++11 -O0 -g -Wallgave me no warning at all, gcc 6 or below with the same compiler option generated no warning either. However, gcc 7.1 or above threw a warning "enum constant in boolean context". BTW, you can test it yourself at godbolt.org :)