Two tips for do while

Source: Internet
Author: User

Do {
...
}
While (0); // while (false)
TIPS:

1. Use in macros:


See the following situation:
# Define swap (x, y) {int TMP = x; X = y; y = TMP ;}
If this is the case during use:
If (condition) Swap (A, B);

Else {...}
Will be replaced with: If (condition) {int TMP = x; X = y; y = TMP ;};

Else {...}
In this case, a compilation error occurs (a semicolon is added after the braces in the IF Statement ). To avoid this problem:
# Define swap (x, y) do {int TMP = x; X = y; y = TMP;} while (0)

2. Replace the GOTO statement:


The GOTO statement breaks the structure of the program, but the proper use of the GOTO statement is sometimes very useful and can play a lot of code, such:
Int * P = new int;
...
If (condition1 ){
Delete P; // redundant code

Return NULL;
}
Else if (condition2 ){
Delete P; // redundant code

Return NULL;
}
Else if...
...

Return P;
In this way, useGoto
Statement to reduce redundant code:
If (condition1) goto failure
;
Else if (condition2) goto failure
;
Else if...
...
Return P;
Failure:
Delete P;
Return NULL;

UseDo... while
The same effect can be achieved, and the structure is better:
Int * P = new int;
...
Do {
If (condition1) Break
;
Else if (condition2) Break
;
Else if...
...
Return P;

} While (0 );
Delete P;
Return NULL;

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.