Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a using declaration legal inside a switch statement before any cases?

The following code compiles fine in GCC 9.1 (-Wall -Wextra -Werror -g) without any warnings or errors, but clang-tidy gives me OCDFAInspection warning: unreachable code. Since GCC has all these addons like integer ranges in switch cases for example, I am concerned, that this might be another addon and not actually valid C++.

So is the following code legal in C++ (17 if that matters)?

namespace foo {
    void bar() {}
}

int main() {
    int n = 42;

    switch (n) {
        using namespace foo; // <- is this valid?
        case 42: 
            bar();
            break;
        default: 
            break;
    }
}
like image 251
nada Avatar asked Sep 05 '25 22:09

nada


1 Answers

The switch statement is a fun one, because the syntax of it is something like

switch (expression) statement

And here statement can be any statement. The compiler treats the keyword case, default and break differently in the scope of a switch but otherwise you can have any statement you want, including block statements (curly-brace enclosed lists of statements) with anything you want.

The problem with generic statements outside of a case is that they won't be executed. The generated code will jump to a specific case label (or the default case), skipping any statements that are not part of a case.

But for this specific case it is, as mentioned in a comment, a false positive. The using directive as used here is directing the compiler to add the namespace foo to its symbol look-up, but it doesn't itself create or generate any executable code.

like image 54
Some programmer dude Avatar answered Sep 08 '25 10:09

Some programmer dude