Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC switch on enum, retain missing warning but use default

Tags:

Using GCC, if you switch on an enum value and one of the enums is missing a case statement a warning will be emitted. When you add a default item the warning will no longer be emitted, which makes sense in the general case.

Is there a way to use a default statement and still have a warning if not all the enum values are covered? Since my function may deal with impure input I'd like to cover the generic case but still get compiler warnings about missing an enum case.

Currently I end up assigning a default after the switch statement.

like image 848
edA-qa mort-ora-y Avatar asked Mar 23 '11 08:03

edA-qa mort-ora-y


2 Answers

-Wswitch-enum, but unluckily only the most recent version supports this.

(You could of course simulate the behaviour that you want by using a goto outside the switch and omitting the default, but I would strongly advise against that, it's ugly and someone else reading your code would have a WTF experience.)

like image 194
Damon Avatar answered Sep 20 '22 15:09

Damon


After reading the link from "David Rodríguez - dribeas", I thought it would be helpful to summarise the options listed there.

There are two ways to do this - either turn the messages about missing enum cases on for all switch statements, then disable it for the ones you don't care about, or leave it at the default and force the errors on for those switch statements you really care about.

Option 1: Warnings for all, mark some as silent

First, add -Wswitch-enum to your compiler flags, so that all switch statements, even ones with a default clause, will have warnings generated if an enum is not handled.

Then, for those switch statements where you want the default case to take care of things and don't want to see warnings, wrap the switch statement like this:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"

switch () {
    ...
}

#pragma GCC diagnostic pop

This will temporarily disable the -Wswitch-enum flag (hiding the warnings about missing enum cases) just for that case statement.

Option 2: Only warn when flagged to do so

Since the default GCC behaviour is to hide warnings when a default clause is present, the compiler flags don't need to be changed for this option.

Instead, for those switch statements that include a default clause, but you still want to see warnings about missing enum cases, wrap the switch like this:

#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wswitch-enum"

switch () {
    ...
}

#pragma GCC diagnostic pop

This temporarily enables the -Wswitch-enum flag between the push and pop lines, causing messages about missing enum cases to be displayed even when a default clause is present. You can change the word warning to error if you want compilation to fail on a missing case.

like image 42
Malvineous Avatar answered Sep 22 '22 15:09

Malvineous