do { ... } while (0) is a C idiom that executes a block exactly once while appearing syntactically like a loop. Compilers optimize it away completely, producing no extra machine code. It's commonly used in function macros to safely wrap multiple statements and enforce semicolon syntax.
Use do-while(0) in macros to enable safe statement grouping and prevent control flow issues.
This example shows do-while-0 wrapping multiple statements in a function macro.
// compile: gcc -o dowhile dowhile.c // run: ./dowhile // description: do-while-0 enables safe multi-statement function macros #include <stdio.h> #define LOG_ERROR(fmt, ...) do { \ fprintf(stderr, "[ERROR] " fmt "\n", ##__VA_ARGS__); \ perror("System error"); \ } while (0) int main() { if (1) { LOG_ERROR("Failed to open file"); } return 0; }