Site Tools


c-do-while-0

C do-while-0

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.

Example

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;
}

Common patterns

Why do-while-0 is needed:

  • Wraps multiple statements into single unit
  • Allows break for early exit without goto
  • Handles trailing semicolon safely

Semicolon handling:

  • User writes MACRO; with semicolon
  • Macro ends with while(0), not while(0);
  • Extra semicolon is benign

Compiler optimization:

  • Compiler removes the loop (condition always false)
  • Zero runtime overhead
  • Same as inline { } block

When to use:

  • Multi-statement macros in conditionals
  • Cleanup/error handling in macros
  • Backward-compatible C code
c-do-while-0.md · Last modified: by 127.0.0.1