2012-09-03 79 views
1

可能重复:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?奇怪宏声明

探索的libusb-1.0.9的源代码,我已发现这样的行(./os/poll_windows.c:78):

#define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0) 

至于我这是一样的:

#define CHECK_INIT_POLLING if(!is_polling_set) init_polling(); 

是否有任何理由循环该表达?

UPDATE:

我仍然不能意识到什么了是答案后错了,下面的例子帮助:

#include <stdio.h> 

#define TEST if(test) foo(); 
#define TEST_DO do { if(test) foo(); } while(0) 

int test = 1; 
void foo() { 
    printf("%s", "Foo called"); 
} 

int main(int argc, char** argv) { 
    if(argc > 1) TEST_DO; /* LINE 12 */ 
    else printf("%s", "skipping..."); 

    return 0; 
} 

如果你把TEST在第12行,编译器将出现错误"error: ‘else’ without a previous ‘if’"
希望,这将有助于某人。

+4

http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for – pyCthon

回答

5

这是为了避免在宏被替换后出现的错误,例如,想想如果第二个版本后有else会发生什么。