Learn C
#include "functions/variadic_functions.h"

Variadic Functions (stdarg) in C

#concept

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).

#how it works
1

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.

2

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.

3

Close with va_end

va_end(ap) in the same function, every path — skipping it is undefined behavior on some platforms.

4

Mind promotions

char/short arrive as int, float as double — va_arg must name the promoted types, never the originals.

#example
#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;
}
Output
60
1n = 3 anchors the walk — the function trusts the caller that three ints follow.
2Three va_arg(ap, int) pulls accumulate 10 + 20 + 30 into total.
3va_end closes the list and 60 prints — miscounted callers would read garbage instead.
#use cases
printf-style logging and formatting helpers
Sentinel-terminated option lists (exec-style NULL endings)
Understanding how the real printf consumes its arguments
Avoiding new variadics where fixed signatures or structs suffice

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.