简单总结就是linux编程下为了规范代码使用,规避分号带来的歧义,加{}形成代码块隔离区域变量冲突而使用
多用在#define宏定义结构下,替换后整体完整且规范
原解释如下
Why do a lot of #defines in the kernel use do { ... } while(0)?
There are a couple of reasons:
(from Dave Miller) Empty statements give a warning from the compiler so this is why you see #define FOO do { } while(0).
(from Dave Miller) It gives you a basic block in which to declare local variables.
(from Ben Collins) It allows you to use more complex macros in conditional code. Imagine a macro of several lines of code like:
Now imagine using it like:
This interprets to:
As you can see, the if then only encompasses the printf(), and the do_something_useful() call is unconditional (not within the scope of the if), like you wanted it. So, by using a block like do { ... } while(0), you would get this:
Which is exactly what you want.
(from Per Persson) As both Miller and Collins point out, you want a block statement so you can have several lines of code and declare local variables. But then the natural thing would be to just use for example:
However that wouldn't work in some cases. The following code is meant to be an if-statement with two branches:
But it would be interpreted as an if-statement with only one branch:
The problem is the semi-colon (;) coming directly after the block. The solution for this is to sandwich the block between do and while (0). Then we have a single statement with the capabilities of a block, but not considered as being a block statement by the compiler. Our if-statement now becomes: