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:
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;
}
-Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. Suppress warning messages emitted by #warning directives.
To answer your question about disabling specific warnings in GCC, you can enable specific warnings in GCC with -Wxxxx and disable them with -Wno-xxxx. From the GCC Warning Options: You can request many specific warnings with options beginning -W , for example -Wimplicit to request warnings on implicit declarations.
By default, Fuchsia C/C++ code compiles with the flag -Wconversion , which prohibits implicit type conversions that may alter a value.
-Werror causes all enabled warnings to cause compilation errors.
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);
}
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