Variadic Macros (__VA_ARGS__) in C
Variadic macros (C99) accept varying arguments like variadic functions: #define LOG(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__) forwards any arity to fprintf, stamping file/line context around user messages. GCC's ##__VA_ARGS__ extension swallows the preceding comma when empty, keeping zero-extra-arg calls compiling.
They combine preprocessor context capture (__FILE__, __LINE__, __func__) with printf-style flexibility — the standard logging/assertion macro shape. Same caution as functions: arguments may evaluate multiple times if referenced twice, so route them through single-use temporaries inside.
Forward with __VA_ARGS__
#define LOG(fmt, ...) fprintf(stderr, "%s:%d: " fmt "\n", __FILE__, __LINE__, __VA_ARGS__) — context plus message in one call.
Empty-args comma swallowing
GNU ##__VA_ARGS__ drops the preceding comma when no extra args arrive — LOG("hi") compiles instead of stranding a comma.
Count arguments (advanced)
PP_NARG tricks count __VA_ARGS__ length for overload-like dispatch — clever, write-once macro machinery.
Single evaluation discipline
Reference each argument once inside the expansion, or side-effect arguments execute repeatedly — same rule as function-like macros.
#include <stdio.h> #define LOG(fmt, ...) fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, __VA_ARGS__) int main(void) { LOG("value=%d", 42); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.