We may write or encounter 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; }
You might consider converting two nested switch-case statements to a switch-case statement in the following way:
Generally, the label of Expr1 and EXPR2 is not too much, the value is not too large, you can determine the maximum label value of EXPR2, you can determine the maximum number of digits required to express EXPR2 Expr2_max_bit, and then put EXPR2 to New_ The low level of expr puts the expr1 in the New_expr high, and then simplifies it to a layer of switch-case.
Examples are 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: This approach does not eliminate the total number of case, but simplifies the logic and code.
C Language Optimization Example: a clever way to eliminate nested switch-case