Question

Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?

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.

Était-ce utile?

La solution

It's to avoid errors that appear after the macro is substituted, for example, think about what happens if there's an else after your second version.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top