Why are C++ switch statements limited to constant expressions?
One of the strengths of C++ is its static checking. The switch
statement is a static control flow construct, whose power lies in the ability to check (statically) whether all cases have been considered, and in being able to group cases sensibly (e.g. fall through common parts).
If you want to check conditions dynamically, you can already do so with a variety of techniques (if
statements, conditional operators, associative arrays, virtual functions, to name a few).
Why are the c++ switch statements limited to constant expressions?
Because the check performed by the switch
statements are static. This means that the expressions need to be known at compile time.
In C++11 you can use constexpr
(if the expressions are derivated by other constant expressions) in your favor. For example consider this function (that replaces your #define
):
inline constexpr int BAND_FIELD1(int B) {
return 10 * B + 1;
}
used in the following simplified version of your code:
constexpr int myField = 0;
constexpr int B = myField % 10;
int variable1 = 0;
switch (myField) {
case BAND_FIELD1(B):
variable1 = 123;
break;
// ...
default: break;
}
As you can see, the above code will easily compile.
The compiler can generate the fastest possible code for a switch when presented with constants--e.g. jump tables or binary search trees.
When given non-constant values, it can't generate code that's any faster than chained if
-else
statements. Which you already have at your disposal anyway!