Compiler support for switch-case error detection
By Urs Fässler
Not adding a default label to the switch-case statement improves the C++ code quality. The normal use case for a switch-case is over an enum like in the example below.
enum class Op {
Addition,
Subtraction,
};
double execute(Op op, double left, double right) {
switch (op) {
case Op::Addition:
return left + right;
case Op::Subtraction:
return left - right;
}
return {};
}
All the enum options have to be considered in the switch-case (if this is not the case then probably something else is a bit smelly in the code).
The compiler is telling us whenever we missed an enum options.
In gcc it is the -Wswitch
flag, this comes for free with -Wall
.
The benefits are:
- Whenever we extending the enum the compiler is helping by telling us where we missed a code change.
- The intent of the code is clear because the normal case is separated from the error case (the error case should be unreachable, but this is a different topic).