C Language Optimization Example: a clever way to eliminate nested switch-case

Source: Internet
Author: User
Tags case statement nested switch

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.