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;