Recently see the C language project in the macro definition used Do...while (0), feel is a knowledge point, special to summarize.
First look at this sentence:do{...} while (0) is the only constructor in C that allows you to define a macro that always works the same way, so that no matter how the macro is used (especially if the statement that calls the macro is not surrounded by curly braces), the semicolon behind the macro is the same effect. the meaning of this sentence is that all statements contained in the macro definition using Do...while (0) are a block of code that is not affected by {};
See an example:
#include <stdio.h> #include <stdlib.h> #define TEST (p) do { if (p!=null) {free (p); printf ("Free success!\n"); } P=null; } while (0) int main () { int *p=null; p= (int*) malloc (sizeof (int)); TEST (p); printf ("---------done!---------\ n"); return 0;}
The function of this line is that the statement is not finished, and the next line is joined with the previous line.
Let's look at an example of error:
Macro definition: #define FOO (x) bar (x); Baz (x)
Then call: foo (x); This is based on the principle of macro substitution: bar (x); Baz (x); that's right!
But if so: if ()
Foo (x)
will be replaced by: if ()
Bar (x);
Baz (x); This is obviously not the same as what we want to do!
Why not use curly braces 直接
to surround a macro? Why do you have to use do/while (0) logic?
Follow the example above:
if
()
{
bar(wolf);
baz(wolf);
}; //最后会添加;,在语法上是错误的!
Use Do...while (0) in the
C language macro definition