Value of Do{}while (0) When macro definition (#define) in C language
Recently found in the code of the new company everywhere used do{...} while (0), Google a bit, found that stack overflow early on a lot of discussion, summed up the discussion, coupled with their own understanding, do{...} while (0) the value is mainly reflected in:
1. Increase the adaptability of the Code
The following macro definition does not use do{...} while (0)
#define FOO (x) foo (x); Bar (x);
Such a macro definition will not have problems with separate calls, such as:
FOO (+)
After the macro expands, it becomes:
This calls Foo without any problems, but Foo (x) cannot be placed in a control statement, such as
1234 |
if (condition) FOO(x); else ...; |
After the macro is expanded, it becomes
If (condition) foo (x); bar (x); else ...;
This leads to grammatical errors , syntax errors are not scary, in the compilation phase can be found, the more deadly is that he may lead to logic errors , this error compiler can not find that the problem, the programmer is crazy. For example:
If (condition) FOO (x);
This code has been expanded to become:
If (condition) foo (x); bar (x);
This will be called regardless of whether condition is true or False,bar (x). Are there any brothers who have been tortured by this?
This time do{...} while (0) the value is reflected, modify the definition of Foo
#define FOO (x) do {foo (x), bar (x);} while (0)
So foo, put in the control statement there is no problem.
Maybe someone said, "Put Foo (x); bar (x) in curly braces?" For example, this defines:
#define FOO (x) {foo (x); bar (x);}
Then look at the following code:
If (condition) FOO (x); else ...;
After expansion:
If (condition) // Note the last semicolon, syntax error else ...;
Still grammatical error;
2. Increase the extensibility of the Code
I understand that extensibility, mainly in macro definitions, can also refer to other macros, such as:
#define FOO (x) Do{other_foo (x)} while (0)
So we don't have to worry about Other_foo. But the statement or the statement, there is no problem
3. Increase the flexibility of the Code
The flexibility is mainly in that we can break out of a macro, such as the following definition:
#define FOO (x) do{\ FOO (x); if(condition (x)) break ; bar (x) ...
} while (0)
Value of Do{}while (0) When macro definition (#define) in C language (GO)