Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a warning for assigning an enum variable with a value out of the range of the enum?

Tags:

c

gcc

gcc-warning

I have a C function which uses an enum as parameter, like the example bellow:

typedef enum
{
  AB, 
  CD
} A;

void f(A input)
{
  // do something
}

int main(void)
{
   // do something
   f(-10);
   // do something
}

Is there a warning that I can enable for assigning an enum variable with a value out of the range of the enum?

like image 390
Felipe GM Avatar asked Dec 15 '25 04:12

Felipe GM


1 Answers

There is an open bug for it in the GCC bug database. It seems that GCC does not contain such a feature yet. There is an option called -Wc++-compat which would complain - among myriad other things, about any integer being converted implicitly to an enum type.

A related feature has just landed into the GCC repository. In GCC trunk (but not in 9.2.1 which is the compiler of Ubuntu 19.10), there is a switch -Wenum-conversion, which would warn about the use of an unrelated enum value, but not a bare integer; i.e. with the code below it will warn about the latter function call, but not the former.:

typedef enum{ AB, CD } A;

typedef enum{ EF, GH } B;

void f(A input){
    (void)input;
}

int main(void){
    f(-10);
    f(GH);
}

The diagnostics from compiling with -Wenum-conversion would be

<source>: In function 'main':
<source>:18:6: warning: implicit conversion from 'enum <anonymous>' to 'A' [-Wenum-conversion]
   18 |    f(GH);
      |      ^~
like image 112