[Bug c++/97266] "enum constant in boolean context" warning seems incorrect

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Thu Oct 1 19:08:54 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97266

--- Comment #1 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to m farazma from comment #0)
> ```
> #include <iostream>
> 
> enum ValidateFlag : int8_t {
>    a = 0, b , c
> };
> 
> int main(){ 
>   bool t = static_cast<bool>(c);
>   return static_cast<int>(t);
> }
> ```
> 
> Compiling the above code with `g++ -Wall test.cc` generates this warning:
> 
> warning: enum constant in boolean context [-Wint-in-bool-context]
> 
> The behaviour doesn't seem correct as `c` is just an `int8_t` value,

No it isn't. In C enumerators are just integers, but in C++ they have the same
type as the enumeration type they belong to.

> and
> casting an `int8_t` value to `bool` does not generate any warnings:
> 
> ```
>   int8_t c = 2;         
>   bool t = static_cast<bool>(c);
>   return static_cast<int>(t);
> ```

I don't know why this is different. I would expect them to be consistent.


> Having only 2 values in the enum also makes it compile fine:
> ```
> enum ValidateFlag : int8_t {
>    a = 0, c
> };

In this case c=1 so there's no change in value when casting to bool. The
warning is for uses of integers other than 0 and 1.


More information about the Gcc-bugs mailing list