do{
// Business logic
}while(false);
Copy the code
I found a strange code in the company reading the project code, which aroused my curiosity. After searching the information, I found that this has the following wonderful use, hereby record.
-
Implement goto-like functions to simplify code nesting
In code, it’s not unusual for a second judgment to depend on the result of the first judgment, or even a third judgment to depend on the result of the second judgment. The conditional judgment can only be written in the following form. This is also a lot of logical code if… Else is one of the reasons for nesting many layers.
if(condition1){ // code segment 1 if(condition2){ // Code segment 2 if(condition3){ // code segment 3}}}Copy the code
But nested judgments make it hard to untangle code logic and error-prone. If you use do… While solves this multiple nesting problem
do{ if(! condition1)break; // code segment 1 if(! condition2)break; // Code segment 2 if(! condition3)break; // code segment 3 }while(false) Copy the code