Search code examples
c++switch-statement

Why are C++ switch statements limited to constant expressions?


I wanted to use macro functions in switch statements before I realized the statements need to be constant. Example (does not compile):

#define BAND_FIELD1(B)   (10 * B + 1)
...
#define BAND_FIELD7(B)   (10 * B + 7)

int B = myField % 10;
switch (myField) {
    case BAND_FIELD1(B):
        variable1[B] = 123;
        break;
    case BAND_FIELD7(B):
        variable7[B] = 321;
        break;
    ...
}

I rather had to use if .. else:

if (myField == BAND_FIELD1(B)
    variable1[B] = 123;
else if (myField == BAND_FIELD7(B)
    variable7[B] = 321;

Why are the C++ switch statements limited to constant expressions?


Solution

  • 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).