0 day streak
c / intermediate
Snippet

Safe Multi-statement Macros with do-while(0)

Wrapping multi-line macros in a 'do { ... } while(0)' block ensures they behave like a single statement, preventing logical errors when used inside 'if' or 'else' blocks without braces.

snippet.c
c
1
2
3
4
5
6
7
#define SWAP(a, b) do { \
int temp = a; \
a = b; \
b = temp; \
} while (0)
if (condition) SWAP(x, y);
Breakdown
1
do { ... } while (0)
Creates a single-execution loop that forces the use of a semicolon at the call site.
2
int temp = a;
Defines a local scope for the temporary variable, avoiding name collisions.