In the Linux kernel code, we often see the do... while (0) Macro. do... while (0) has many functions. Below are a few examples:
URL: http://www.cnblogs.com/archimedes/p/do-while-0.html.
1. Avoid the goto statement:
Generally, if a function needs to allocate some resources at the beginning, and then exits the function if an error occurs midway through, of course, to release the resource before exiting, our code may be as follows:
* P = (*) malloc (N * (bOk = (! = (! = (! =View Code
The biggest problem here is code redundancy. Every time an operation is added, corresponding error handling is required, which is very inflexible. So I thought of goto:
* P = (*) malloc (N * (bOk = (! BOk) = (! BOk) = (! BOk) =View Code
Code redundancy is solved, but the subtle goto statements in the C language are introduced. Although correct use of the goto statement can greatly improve the flexibility and simplicity of the program, it will make our program confused, to avoid using the goto statement and eliminate code redundancy, consider the following do... while (0 ):
* P = (*) malloc (N * (bOK = (! BOK) = (! BOK) = (! BOK)} (=View Code2. Avoid empty declaration warnings during compilation:
In the Linux kernel source code, the following macros are often seen to avoid warnings during compilation:
FOO do { } while(0)
3. Compile a code block that meets your habits:
You may often use the following macros:
exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }
However, in some cases it will become invalid. The following code uses if... else...
(x >
But it will be interpreted as the if statement of a branch:
(x >=== do_something();
The error ";" is directly behind the code block. The solution is to embed the code into do... while (0) and get the following code:
(x >===(
The macro above can be modified:
exch(x,y) do {\ ===()
4. Use complex Macros in condition statements:
Suppose a macro contains several lines of code similar to the following:
FOO(x) \
Now, imagine the following code:
(blah ==
(blah ==
(blah == ();
FOO(x) do { \ ()