c / intermediate
Snippet
Safe Multi-line Macros with do-while(0)
Wrapping a multi-statement macro in a 'do { ... } while (0)' block ensures it behaves as a single statement. This prevents logical errors when the macro is used inside 'if' statements without curly braces and forces the user to provide a semicolon.
snippet.c
1
2
3
4
#define SAFE_FREE(ptr) do { \free(ptr); \ptr = NULL; \} while (0)
Breakdown
1
do { ... } while (0)
Creates a scope that executes exactly once and requires a trailing semicolon.
2
ptr = NULL;
Ensures the pointer is invalidated after freeing to prevent dangling pointers.