c++visual-c++-2008

Compiler warning when switching on an enum


enum ENUM(Option1,Option2,Option3);

string func(ENUM x)
{
 switch(x)
 {
  case Option1: return "Option1";
  case Option2: return "Option2";
  case Option3: return "Option3";
 }
}

This compiles and works but gives a compiler warning that not all control paths return. However isn't the point that if you use enums properly, this isn't the case? If another ENUM val is added, I want compilation to fail but as long as all cases are covered I want it to compile warning-free.

Is this the compiler protecting against bad casted values, is it just part of C++ and needs to be lived with?


Solution

  • What happens if for some reason x is neither Option1, nor Option2, nor Option3?

    Sure, you could argue that will never happen, but since the method has to return something, you have two options:

    As CodeGray points out, the second option is arguably better style. You could also return something other than an empty string.