Blank Default Case in C++ Switch Statement

Thank you in advance for sharing your knowledge!

I am working on someone else's C++ code (cannot share the code here for legal reasons), and they continue to use switch statements in a way that doesn't make sense to me.

This coder leaves blank default cases in all of his switch statements.
Is there a benefit to doing that? Why would someone create the default case and then leave it blank? ...what goes on under the hood in C++ that might make this advantageous....?

That's defensive coding.

With a debug build if you execute a switch statement for an index for which there is no matching case branch and no default case, you're likely to get a run time exception.

Executing a release build under the same conditions results in undefined behavior.


Edit: Corrected per C++ spec 6.4.2.5:
If no case matches and if there is no default then none of the statements in the switch is executed.
Last edited on
With a debug build if you execute a switch statement for an index for which there is no matching case branch and no default case, you're likely to get a run time exception.

That's not true. If there is no matching case (or default) then the switch statement doesn't do anything.

But I think AbstractionAnon is right this this is defensive programming. The coder just wanted to make it clear that he/she had thought of the default case and decided that no action was required.

I know a guy who writes an else with every if for just this reason. It forces him (and you, the person maintaining the code) to think about what should happen if the condition is false.
I sometimes do it to avoid compiler warnings.

If you use the GCC flag -Wswitch (one of the flags turned on by -Wall) it will warn you if you use an enum in a switch and don't handle all the enum values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

enum E
{
	e1,
	e2
};

void foo(E e)
{
	switch (e) // warning: enumeration value ‘e2’ not handled in switch [-Wswitch]
	{
	case e1:
		std::cout << "Yay!" << std::endl;
	}
}


Adding a default case gets rid of the warning.
Last edited on
Topic archived. No new replies allowed.