Compiler not warns about "int in bool context"

Viewed 185

In my project I changed many of our function's return value from bool to enum value
The problem is in the integration. The compiler doesn't warn me about wrong use of the functions.

I'm using g++ (with c++14) and with "-Wall -Wextra -Werror" flags

Lets see an example which produces the warning:

typedef enum {
    VALUE_1,
    VALUE_2,
    VALUE_3
} MY_ENUM;

bool bar() {
    return VALUE_3;
}

So in this example we return VALUE_3 and get error correctly: error: enum constant in boolean context [-Werror=int-in-bool-context]

But, if we change this example a bit, the compiler will not produce any errors:

typedef enum {
    VALUE_1,
    VALUE_2,
    VALUE_3
} MY_ENUM;

MY_ENUM foo() {
    return VALUE_3;
}

bool bar() {
    return foo();
}

Of course I understand that enum is type of int, and bool is a type of int so the compiler can process it. But at least I expect for some kind of warning?

Tried with clang too, same results with both examples.
The problem in my project is that I changed about ~150 function's return values, and there are about ~300 calling. So without any warnings I easily miss some...

Can I get it somehow to yell at me?

1 Answers

Couple Ideas:

  1. Have a look here at some different flags:

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Add in -Wextra. The site says not all warnings are explicitly added by -Wall and may need explicitly added. Note implicit conversion for enum is c only. Looks like you tagged c++.

  1. Also see

Warnings or errors for C++ implicit conversion of primitives

about primitive conversions.

  1. Enum class will not convert to int if you want to be really specific about using the enum value and therefore will give an error in bool context.

Hope this gets you somewhere.

Related