Strange macro declaration in C
Posted
by
Andrey Atapin
on Stack Overflow
See other posts from Stack Overflow
or by Andrey Atapin
Published on 2012-09-03T03:03:39Z
Indexed on
2012/09/03
3:38 UTC
Read the original article
Hit count: 132
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.
© Stack Overflow or respective owner