Warning: enumeration value not specifically handled in switch (JUCE 6)

I compiled my project in JUCE 6 for the first time today (Mac OS X). I am getting a new compiler warning that I have not seen before, which is:

enumeration value ‘blah-blah’ not specifically handled in switch

For example, if you have:

enum class Type
{
	apple = 0,
	orange,
	banana,
	peach,

	numTypes
}

And then:

void myClass::foo(Type type)
{
	switch (type)
	{
		case Type::apple:
			// do something
			break;
		case Type::orange:
			// do something
			break;
		default:
			// do something
			break;
	}
} 

You then get compiler warnings:

enumeration value ‘banana’ not specifically handled in switch
enumeration value ‘peach’ not specifically handled in switch
enumeration value ‘numTypes’ not specifically handled in switch

…even though you have a default case that handles all other enum values!

To fix this, you actually have to do something like:

void myClass::foo(Type type)
{
	switch (type)
	{
		case Type::apple:
			// do something
			break;
		case Type::orange:
			// do something
			break;
		case Type::banana:
		case Type::peach:
		case Type::numTypes:
		default:
			// do something
			break;
	}
} 

If your enum has 30 or 40 values, you would have to explicitly list every single one!

This is due to this warning flag (in Apple Clang-Custom Compiler Flags > Other C++ Flags)

-Wswitch-enum

Changing this to -Wswitch still gives you the warning if there is no default case, but does NOT give you the warning otherwise. This seems more logical to me…

I assume this is inserted by the Projucer option “Add Recommended Compiler Warning Flags”?

According to this there’s just a slight difference between these two:

And that’s why it’s a great warning! When you add a new value, you can’t forget to handle it.

But that’s why you have a default, that handles it. No?

When you add a new value to an enum, that’s usually because you want a new behavior, not the default one.

Yes, in some functions you would want to implement new behavior. In other functions, you would want the default to handle it. I don’t know, this warning seems overkill to me…

3 Likes