cbuchart
cbuchart

Reputation: 11555

Code before first case in switch statement

Please note that this is a question about C++ language, not about how real or useful is the example I'm giving to illustrate it.

Imagine we have an enum in a namespace (or namespaces):

namespace SomeVeryLargeNamespaceExample {
    enum class E {
        One,
        Two,
    };
}

Now, we want to use it in the expression of a switch statement. Today I found that it is possible to add the using SomeVeryLargeNamespaceExample::E inside the switch statement, before the first case, reducing the code cluttering in the cases:

switch (e) {
    using SomeVeryLargeNamespaceExample::E;
case E::One:
    std::cout << "One\n";
    break;
case E::Two:
    std::cout << "Two\n";
    break;
}

At first glance I thought it was some kind of "do this before any case statement" feature that I never learned about, but some expressions, such as a function call, are not executed (actually, gcc generates a warning statement will never be executed [-Wswitch-unreachable]). On the other hand, a variable declaration is possible (but not initialization).

My question is, what other statements are possible? Is this a feature or just a consequence of how switch is designed?

Note: I found this other question, but it is specific for C (so it doesn't mention the namespaces case, for example), and I'm curious about C++.

Upvotes: 4

Views: 837

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

Any valid C++ statement is possible:

int a;

void foo(int x)
{
    switch (x) {
        a=4;
    case 0:
        a=1;
        break;
    case 1:
        a=2;
        break;
    }
}

This is syntactically valid C++, and gcc has no issues compiling it and producing an executable. However the initial statement can never be reached, of course. Therefore every modern C++ compiler will give you a warning message:

t.C: In function ‘void foo(int)’:

t.C:8:18: warning: statement will never be executed [-Wswitch-unreachable]

8 |                 a=4;
  |

Upvotes: 2

Related Questions