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?
What happens if for some reason
xis neitherOption1, norOption2, norOption3?Sure, you could argue that will never happen, but since the method has to return something, you have two options:
add a
return string("");at the end.add a
defaultto theswitchthat returnsstring("").As CodeGray points out, the second option is arguably better style. You could also return something other than an empty string.