This can often be seen in open-source software.
#define X(a) do { f1(a); f2(a); } while(0)
1. The main role is to put in the macro definition inside , to avoid the grammar problems caused by macros.
Like what
#define DoSomething () cmd1; CMD2;
And when the call
if (a>0) dosomething (); There will be a problem, need to use the above mentioned
And then, why not use if (1) {...} ?
There are two reasons :
First, there will be more unnecessary semicolons, such as:
if (1) my_code;
另外更重要的是,有if-else的问题:
if ( Span class= "lit" >1) My_code;else { ... /span>
Of course, if defined as
#define X (a) if (1) {a F2 ( a); } else{}
is as secure as the Do...while (0) below. But the above if-else notation does not need to write a semicolon; there are pros and cons .
#define X(a) do { f1(a); f2(a); } while(0)
2. Another important reason is that it can be used instead of a goto jump .
For example, the following goto code:
int foo () { somestructmalloc(...); DoSomething ...; if (Error) { goto END; } DoSomething ...; if (Error) { goto END; } DoSomething ...; END: free(PTR); return 0 ; }
You can use the Do...while (0) and break mates to write:
intfoo () {somestruct* ptr =malloc(...); Do{dosomething ...; if(Error) { Break; } dosomething ...; if(Error) { Break; } dosomething ...; } while(0); Free(PTR); return 0; }
Goto is converted to do...while+break, and there are many advantages in program structure and compilation optimization. I think.
3, avoid the warning caused by the empty macro
Because of the limitations of different architectures in the kernel, many times use empty macros, when compiling, the empty macro will give warning, in order to avoid such warning, you can use Do{}while (0) to define the empty macro:
#define EMPTYMICRO do{}while (0)
I think this can be replaced by If-else.
4. Define a separate function block to implement complex operations, avoiding scope or namespace collisions
When your function is very complex, many variables you do not want to add a function, use Do{}while (0), and write your code inside, you can define the variable without considering the variable name in conjunction with the function before or after the repetition .
Finish
C + + do{...} while (0) benefits