Possible en double:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?déclaration macro étrange dans C
Explorer le code source libusb-1.0.9, j'ai trouvé cette ligne (./os/poll_windows.c:78
):
#define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0)
Comme pour moi c'est la même chose comme:
#define CHECK_INIT_POLLING if(!is_polling_set) init_polling();
Y a-t-il une raison pour boucler cette expression?
MISE À JOUR:
Je ne pouvais pas réaliser encore qu'as tort après les réponses, et l'exemple suivant aidé:
#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;
}
Si vous mettez TEST
à la ligne 12, un compilateur donnera une erreur "error: ‘else’ without a previous ‘if’"
.
Espérons que cela aidera quelqu'un.
http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for – pyCthon