1

Following the code from here:

enum class OS_type { Linux, Apple, Windows };

const std::string ToString(OS_type v)
{
    switch (v)
    {
        case Linux:   return "Linux";
        case Apple:   return "Apple";
        case Windows: return "Windows";
        default:      return "[Unknown OS_type]";
    }
}

I want to remove default and instead force compiler to generate error if the switch is not complete over my enum.

Community
  • 1
  • 1
barej
  • 1,330
  • 3
  • 25
  • 56

1 Answers1

2

GCC / Clang

You are looking for -Wswitch-enum.

Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label.

const std::string ToString(OS_type v)
{
    // warning: enumeration value 'Windows' not handled in switch [-Wswitch-enum]
    switch (v)
    {
        case OS_type::Linux:   return "Linux";
        case OS_type::Apple:   return "Apple";
        default:      return "[Unknown OS_type]";
    }
}

Even default is used, it complains about the missing Windows enum. Just create the case for Windows and make a fallthrough to the default to suppress the enum.

Visual Studio

VS handles this at compiler level 3 and 4. You need to enable warning C4061 / C4062. https://msdn.microsoft.com/en-US/library/96f5t7fy.aspx

HelloWorld
  • 2,392
  • 3
  • 31
  • 68