A popular saying on the Internet recently is: Yuan Fang. What do you think? So do {…} used in the macro definition in the Linux Kernel {...} While (0), Yuan Fang, what do you think?
If you know the truth, write a few lines of code for debugging. There are too many wonderful uses in the Linux kernel. The wealth accumulated by humans, unlike windows, Linux allows me to see and learn. For Windows, you can only write the APIS they have prepared and call the functions.
Let's take a look at the code first:
#include <stdio.h> void aa(void){ printf("%s\n",__func__);}void bb(void){ printf("%s\n",__func__);}#define myfunc(tmp) do{ if(tmp) aa();}while(0)//#define myfunc(tmp) if(tmp) aa()#define myswap(x, y) do{int temp = x; x = y; y = temp;}while(0)//#define myswap(x, y) {int temp = x; x = y; y = temp;}int main(void){ int n = 0; int a = 2; int b = 8; myswap(a, b); printf("a = %d, b = %d\n", a, b); if(n) myfunc(1); else bb(); return 0;}
Two macros are defined here. Each macro uses two methods, plus do {...} While (0) and not added. For the first macro
#define myfunc(tmp) do{ if(tmp) aa();}while(0)
We can know that if the input parameter TMP is true, print AA. If the input TMP is false, print BB. This is easy to understand. Split the code in the main function.
if(n) myfunc(1);else bb();
========>>
if(n) do{ if(1) aa();}while(0) ; else bb();
This is correct.
However, if do {…} is not added {...} What about while (0?
#define myfunc(tmp) if(tmp) aa()
Let's take a look at the code in the main function.
if(n) myfunc(1); else bb();
========>>
if(n) if(1) aa(); else bb();
Else will never run here. We can see that do {...} While (0) is one of the advantages.
Then there is the second macro.
#define myswap(x, y) do{int temp = x; x = y; y = temp;}while(0)
Split in Main Function
Myswap (A, B );
========>>
do{int temp = a; a = b ;b = temp;}while(0);
The exchange function is implemented.
While
#define myswap(x, y) {int temp = x; x = y; y = temp;}
Split in Main Function
Myswap (A, B );
========>>
int temp = a; a = b ;b = temp;;
An empty statement is added.
This is do {...} The benefit of while (0) is second.
I don't know who thought of it. What's the subtlety of the program.