#For production of errors on missing case for enum type

25 messages · Page 1 of 1 (latest)

shy girder
#

I have the following code:

enum SpeedMode {Slow, Medium Fast};
SpeedMode mode = SpeedMode::Slow;

void foo (void) {
    switch (mode) {
        case SpeedMode::Slow: // something
        case SpeedMode::Fast: // somthingier
        //case SpeedMode::Medium: /*missing*/
    }
}

I want to have gcc produce an error in this situation to make sure it doesn't get just a warning. Furthermore, I want to make it somewhat inconvenient to just add a default when there really shouldn't be any. Is there a particular attribute or pragma for this?

zenith vaultBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

fossil lance
#

Turn it into an error with -Werror.

#

I'd be interested to learn if you can prevent anyone from adding default to a switch statement.
I fear that may have to be done in a PR/peer review.

#

For MSVC it seems you will just have to add this somewhere globally?

#pragma warning(1 : 4062)

And then set the option to treat warnings as errors in your project settings.

#

If you are using CMake, then you can use

set(CMAKE_COMPILE_WARNING_AS_ERROR ON)

(untested)

blissful pike
#

-Wswitch-enum

#

just found that

#

warns even if you have default but still arent covering all enum values (explicitly)

zenith vaultBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.

shy girder
#

Yeah but what if I want only this case to generate errors and not all warnings to become errors?

slender basin
#

you might be able to add some pragmas

#

but you'd need to do that for basically every compiler you use

#

and, further, then you'd probably want to add a bunch of #ifdef so you don't get warnings about unknown pragmas

fossil lance
#

warns even if you have default but still arent covering all enum values (explicitly)

Related, but an aside:
My clang-format moans like a little bitch if I have a default in my switch that already covers all enums.

blissful pike
#

clang tidy false positives make me go insane I want everything to look clean but it forces me to do //NOLINT

#

wait clang format or clang tidy?

fossil lance
#

Oh, IDK. One of them.
Forced upon me by management.

shy girder
little island
#

I will just note that there is pain associated with this, because ```cpp
enum class E { a, b, c };
void foo(E e) {
switch (e) {
using enum E;
case a: x();
case b: y();
case c: z();
}
}

// OK
foo(static_cast<E>(42));