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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With