Personal classification: Design C/C ++
Today, I found a style that I don't quite understand. Some codes are segmented and contained in the do {...} while (false) interval. In general, do while is used for loop, but here the loop condition is false, there will be no loop at all, so what is the significance?
After checking the Internet, we can conclude that using the do {...} while (false) structure can simplify the nesting of multi-level Judgment time codes.
For example, to implement a function, we need four prerequisites: A, B, C, and D. In addition, both of these prerequisites depend on the upper-level, that is, B depends on, c depends on a and B, and D depends on A, B, and C. If you follow the general syntax, it is as follows:
- If (A = true)
- {
- If (B = true)
- {
- If (C = true)
- {
- If (D = true)
- {
- // Code for implementing the Function
- }
- }
- }
- }
It may be seen that this causes multi-layer if statement nesting, and the logic looks unclear.
One solution is to use the GOTO statement. When a condition fails, the system directly jumps to the following statement segment, as shown in the following figure:
- If (A = false)
- Goto tag;
- If (B = false)
- Goto tag;
- If (C = false)
- Goto tag;
- If (D = false)
- Goto tag;
- // Code for implementing the Function
- Tag:
- ...
The style looks much better, but it is not recommended to use the GOTO statement.
In fact, you can use the do while statement to implement similar goto functions, but the code is much easier to read than the Goto style. The Code is as follows:
- Do
- {
- If (A = false)
- Break;
- If (B = false)
- Break;
- If (C = false)
- Break;
- If (D = false)
- Break;
- // Code for implementing the Function
- } While (false );
- ...
In this way, you can understand the code segment in do {...} while (false). You can use break to implement a jump function similar to goto, which is very useful in actual projects.
Do ...... while (false)