C do-while-0 is an idiom using do { ... } while(0) to create a single-iteration loop that allows break to exit cleanly. It's used in macros to ensure multiple statements execute as a unit, or to allow early exit without goto or nested conditionals.
Use do-while-0 in macros to wrap multiple statements safely, preventing issues when macros are used in conditionals or with semicolons.
This example shows do-while-0 fixing common macro pitfalls.
// compile: gcc -o do_while do_while.c // run: ./do_while // description: do-while-0 macro pattern #include <stdio.h> #include <stdlib.h> #define LOG_SAFE(msg) \ do { \ printf("LOG: %s\n", msg); \ fflush(stdout); \ } while(0) #define VALIDATE(ptr) \ do { \ if ((ptr) == NULL) { \ fprintf(stderr, "Validation failed\n"); \ break; \ } \ printf("Validation passed\n"); \ } while(0) int main() { if (1) LOG_SAFE("Message"); int *arr = malloc(100); VALIDATE(arr); free(arr); return 0; }
Why do-while-0 is needed:
break for early exit without gotoSemicolon handling:
MACRO; with semicolonwhile(0), not while(0);Compiler optimization:
When to use: