Strange macro declaration in C
- by Andrey Atapin
Exploring libusb-1.0.9 source code, I have found such line (./os/poll_windows.c:78):
#define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0)
As for me this is the same like:
#define CHECK_INIT_POLLING if(!is_polling_set) init_polling();
Is there any reason to loop that expression?
UPDATE:
I couldn't still realize what'd be wrong after the answers, and the following example helped:
#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;
}
If you put TEST at line 12, a compiler will give an error "error: ‘else’ without a previous ‘if’". Hope, this will help someone.