Why does gcc not warn when an enum or int value is passed on as a function's argument which is bool?
c++, g++, gcc, gcc-warning
Solution
Yes, those implicit conversions are perfectly legal.
C++11 draft n3290, §4.12 Boolean conversions:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
Warnings on these conversions (for arithmetic types) would probably lead to huge numbers of warnings all over the place, I don't think it would be manageable.
In C++11, you can use scoped enums to prevent that implicit conversion:
This fails to compile for lack of a conversion from `Foo` to `bool`:
enum class Foo { ONE };
void tryit(bool b) { }
int main()
{
tryit(Foo::ONE);
}
Problem
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 `-Wall -Wextra` options given to the compiler. I have even tried with `-Wconversion` option, which took no 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 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 Editted 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; } ```