c-do-while-0
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| c-do-while-0 [August 22, 2026 at 16:03] – Ivan Janevski | c-do-while-0 [August 26, 2026 at 11:41] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| # C do-while-0 | # C do-while-0 | ||
| - | **[do { ... } while (0)](https:// | + | **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 |
| - | Use `do-while(0)` in macros to enable safe statement grouping and prevent control flow issues. | + | Use do-while-0 in macros to wrap multiple statements safely, preventing |
| ## Example | ## Example | ||
| - | This example shows do-while-0 | + | This example shows do-while-0 |
| ```c | ```c | ||
| - | // compile: gcc -o dowhile dowhile.c | + | // compile: gcc -o do_while do_while.c |
| - | // run: ./dowhile | + | // run: ./do_while |
| - | // description: | + | // description: |
| #include < | #include < | ||
| + | #include < | ||
| - | # | + | # |
| - | fprintf(stderr, | + | |
| - | | + | printf(" |
| - | } while (0) | + | fflush(stdout); |
| + | | ||
| + | |||
| + | #define VALIDATE(ptr) \ | ||
| + | do { \ | ||
| + | if ((ptr) == NULL) { \ | ||
| + | | ||
| + | | ||
| + | } \ | ||
| + | printf("Validation passed\n"); \ | ||
| + | } while(0) | ||
| int main() { | int main() { | ||
| - | if (1) { | + | if (1) |
| - | | + | |
| - | } | + | |
| | | ||
| + | int *arr = malloc(100); | ||
| + | VALIDATE(arr); | ||
| + | | ||
| + | free(arr); | ||
| return 0; | 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/ | ||
| + | - Backward-compatible C code | ||
c-do-while-0.1787414631.md.gz · Last modified: by Ivan Janevski
