c++gccg++gcc-warning

Why does GCC not warn when an enum or int value is passed on as a function's argument which is bool?


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:

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;
}

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);
    }