C Language Optimization Example: To eliminate nesting switch-case smart approach

Source: Internet
Author: User
Tags case statement nested switch

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

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.