Nested switch
structures are difficult to understand because you can easily confuse the cases of an inner switch
as
belonging to an outer statement. Therefore nested switch
statements should be avoided.
Specifically, you should structure your code to avoid the need for nested switch
statements, but if you cannot, then consider moving
the inner switch
to another function.
Noncompliant code example
void func(int n, int m) {
switch (n) {
case 1:
// ...
case 2:
// ...
case 3:
switch (m) { // Noncompliant
case 4: // Bad indentation makes this particularly hard to read properly
// ...
case 5:
// ...
case 6:
// ...
}
case 4:
// ...
default:
// ...
}
}
Compliant solution
void func(int n, int m) {
switch (n) {
case 1:
// ...
case 2:
// ...
case 3:
int m2 = handle_m(m);
case 4:
// ...
default:
// ...
}
}