Learn C
#include "preprocessor/variadic_macros.h"

Variadic Macros (__VA_ARGS__) in C

#concept

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.

#how it works
1

Forward with __VA_ARGS__

#define LOG(fmt, ...) fprintf(stderr, "%s:%d: " fmt "\n", __FILE__, __LINE__, __VA_ARGS__) — context plus message in one call.

2

Empty-args comma swallowing

GNU ##__VA_ARGS__ drops the preceding comma when no extra args arrive — LOG("hi") compiles instead of stranding a comma.

3

Count arguments (advanced)

PP_NARG tricks count __VA_ARGS__ length for overload-like dispatch — clever, write-once macro machinery.

4

Single evaluation discipline

Reference each argument once inside the expansion, or side-effect arguments execute repeatedly — same rule as function-like macros.

#example
#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;
}
Output
[main.c:7] value=42
1The macro pastes file, line, and the user's format plus arguments into one fprintf.
2At line 7, __FILE__ and __LINE__ stamp the call site automatically.
3The message prints self-located — logging with zero manual labels.
#use cases
Debug/info/error logging macros with automatic location stamps
Assertion helpers forwarding custom messages plus context
Optional-argument wrappers around printf-family functions
Counting and dispatching on arity in macro libraries

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.