Reprint address: http://www.spongeliu.com/415.html Linux kernel and some other open source code, often encounter such code:
This code is not a loop at a glance, do. While the surface is meaningless here, why use it so much?
In fact, do{...} while (0) is much more useful than beautifying your code. Looked up some information, summed up this writing mainly has the following points of interest:
1, the auxiliary definition complex macro, avoids the reference error time:
For example, suppose you need to define a macro like this:
#define DoSomething () foo1 (); Foo2 (); |
The intent of this macro is that the function foo1 () and Foo2 () will be called when DoSomething () is called. But if you write this at the time of the call:
Because macros are directly expanded when they are preprocessed, you actually write the code like this:
if (a>0) foo1 (); Foo2 (); |
This causes a problem because the program is executed regardless of whether a is greater than 0,foo2 (), resulting in an error.
So just use {} to wrap foo1 () and Foo2 () together, okay?
When we write code, we are used to add a semicolon to the right of the statement, and if you use {} In a macro, the code is equivalent to this: "{...};", as it unfolds:
if (a>0) { foo1 (); Foo2 ();}; |
This will not even compile through. So, a lot of people have adopted do{...} while (0);
#define DoSomething () do{ foo1 (); Foo2 (); } while (0) ... if (a>0) dosomething (); |
This way, the initial semantics are preserved only after the macro is expanded. GCC provides statement-expressions to replace do{...} while (0); So you can also define macros like this:
#define DoSomething () ({ foo1 (); Foo2 (); }) |
Do{...} The meaning and usage of while (0)