Variadic Functions (stdarg) in C
Variadic functions accept varying argument counts — printf is the archetype. The <stdarg.h> protocol: a fixed first parameter anchors va_start(ap, last_fixed), each va_arg(ap, Type) pulls the next argument (you must name the right type — the compiler can't check), and va_end(ap) closes up. A count, format string, or sentinel tells the function when to stop.
Type-unsafety is total: mismatched va_arg types read garbage, and too few arguments reads off the stack's end. Modern guidance is narrow — logging and formatting need them, almost nothing else does — with careful sentinels and defaults (floats promote to double, chars to int).
Anchor with a fixed param
int sum(int n, ...) — n (or a format string) tells the body how many arguments follow; variadics can't self-describe.
Walk with va_arg
va_list ap; va_start(ap, n); then va_arg(ap, int) per item with the exact promoted type — wrong types read garbage.
Close with va_end
va_end(ap) in the same function, every path — skipping it is undefined behavior on some platforms.
Mind promotions
char/short arrive as int, float as double — va_arg must name the promoted types, never the originals.
#include <stdio.h>#include <stdarg.h> int sum(int n, ...) { va_list ap; va_start(ap, n); int total = 0; for (int i = 0; i < n; ++i) total += va_arg(ap, int); va_end(ap); return total;} int main(void) { printf("%d\n", sum(3, 10, 20, 30)); 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.