do{}while(0)在宏定义中的作用

在开源代码中看到,宏定义经常这样用
[cpp]  view plain  copy
 
  1. #define some()                    
  2.     do {                                  
  3.         do_somt_thing();  
  4.     } while (0)  

为什么这样用?

可以试一下,假如一个普通宏定义

[cpp]  view plain  copy
 
  1. #define some(x) Fun1(x);Fun2(x)  

[cpp]  view plain  copy
 
  1. if(condition)  
  2.     some(x);  

变为

[cpp]  view plain  copy
 
  1. if(condition)  
  2.     Fun1(x);  
  3.     Fun2(x);  

这样直接加个花括号不久行了,为什么还用do......while()?假如加上花括号

[cpp]  view plain  copy
 
  1. #define some(x) {Fun1(x);Fun2(x);}  

[cpp]  view plain  copy
 
  1. if(condition)  
  2.     some(x);  
  3. else  
  4.     someelse(x);  

变为

[cpp]  view plain  copy
 
  1. if(condition)  
  2. {  
  3.     Fun1(x);  
  4.     Fun2(x);  
  5. };//多了个分号  
  6. else  
  7.     someelse(x);  


因此宏定义中使用do...while(0)可以确保不管在代码中怎么使用宏定义,它总是正确的。

你可能感兴趣的:(do{}while(0)在宏定义中的作用)