We may write or encounter a code like this:
C + + Switch(EXPR1) { CaseLABEL11:Switch(EXPR2) { CaseLABEL21://Do something Break; CaseLABEL22://Do something Break;default://Do something Break; } Break; CaseLABEL12:Switch(EXPR2) { CaseLABEL21://Do something Break; CaseLABEL22://Do something Break;default://Do something Break; } Break; CaseLABEL13:Switch(EXPR2) { CaseLABEL21://Do something Break; CaseLABEL22://Do something Break;default://Do something Break; } Break;default://Do something Break; }
It is then possible to consider converting two nested switch-case statements into a switch-case statement in the following way:
Generally, expr1 and expr2 do not have too many label cases. The value is not too large to determine the maximum label value of the EXPR2, and to determine the maximum number of digits required to express EXPR2 Expr2_max_bit. Then put the EXPR2 to new_expr Low, put expr1 to new_expr high, and then simplify to a layer of switch-case.
The scale is as follows:
C + +new_expr = expr1 << expr2_max_bit + expr2;Switch(new_expr) { CaseLabel1://Do something Break; CaseLabel2://Do something Break; CaseLABEL3://Do something Break; CaseLabel4://Do something Break; CaseLabel5://Do something Break; CaseLABEL6://Do something Break;default://Do something Break; }
Note: In this way, the total number of case cannot be eliminated. However, logic and code can be simplified.
C Language Optimization Example: To eliminate nesting switch-case smart approach