The value of do {} while (0) when macro definition (# define) is in C language,
Recently I found that do {...} is used everywhere in the code of the new company {...} while (0), google, I found that there was a lot of discussion on Stack Overflow, summarized the discussion, and added my understanding, do {...} the value of while (0) is mainly reflected in:
1. Added code Adaptability
The macro definition below does not use do {...} while (0)
#define FOO(x) foo(x); bar(x);
In this macro definition, there will be no problems with separate calls, for example:
FOO(100)
After macro expansion, it becomes:
foo(x);bar(x);
There is no problem in calling FOO in this way, but FOO (x) cannot be put into the control statement, for example
if (condition) FOO(x);else ...;
After macro expansion
if (condition) foo(x);bar(x);else ...;
This causesSyntax ErrorThe syntax error is not terrible. It can be found at the compilation stage. what's even more fatal is that it may causeLogical errorThe compiler cannot find this error. When this problem occurs, the programmer will be crazy. For example:
if (condition) FOO(x);
This code is expanded:
if (condition) foo(x); bar(x);
In this way, bar (x) is called no matter whether the condition is true or false. Have you ever been suffering from this?
At this time, the value of do {...} while (0) is reflected. modify the definition of FOO.
#define FOO(x) do { foo(x); bar(x); } while (0)
In this way, there is no problem in putting FOO into the control statement.
Some people may say: Isn't it okay to enclose foo (x); bar (x) in braces? For example:
#define FOO(x) { foo(x); bar(x); }
Let's look at the following code:
if (condition) FOO(x);else ...;
After expansion:
If (condition) {foo (x); bar (x) ;}; // note the last semicolon, syntax error else ...;
Still syntax errors;
2. Added code scalability
I understand the scalability, mainly because other macros can be referenced in the macro definition, such:
#define FOO(x) do{OTHER_FOO(x)} while(0)
In this way, we don't have to worry about whether OTHER_FOO is, but the statement is still consistent with the statement.
3. Added code flexibility
Flexibility is mainly reflected in the following definition:
#define FOO(x) do{ \ foo(x); \ if(condition(x)) \ break; \ bar(x) \ ..... \
} while(0)