</>EmbeddedInterview

How do variadic functions work?

MediumC Programming

Short answer: A variadic function such as printf has at least one fixed parameter followed by .... It reads the extra arguments with the <stdarg.h> macros va_start, va_arg, va_end (and va_copy). The function has no way to know how many arguments were passed or their types, so a fixed parameter (a count or a format string) must tell it.

#include <stdarg.h>
#include <stdio.h>

int sum(int count, ...)
{
    va_list ap;
    int s = 0;
    va_start(ap, count);              /* start after the last fixed parameter */
    while (count--)
        s += va_arg(ap, int);         /* read the next argument as an int */
    va_end(ap);
    return s;
}

/* a logging wrapper that forwards to vprintf */
void log_msg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
void log_msg(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    printf("[%lu] ", (unsigned long)0 /* tick */);
    vprintf(fmt, ap);
    va_end(ap);
}

Rules and pitfalls

  • Default argument promotions apply to the variable arguments: char and short become int, float becomes double. So va_arg(ap, char) or va_arg(ap, float) is wrong; use int and double.
  • Reading more arguments than were passed, or with the wrong type, is undefined behaviour. printf("%d", 3.5) and printf("%s", 42) are classic bugs.
  • The format attribute lets GCC/Clang check format strings in your own wrappers, catching those bugs at compile time.
  • To pass the arguments on, write a v version that takes a va_list (like vprintf), because you cannot forward ... directly.
  • Use va_copy if you need to traverse the list twice.

How it works underneath: on Arm (AAPCS), the first four integer arguments are in registers r0–r3, and the rest are on the stack. va_start makes the callee save the register arguments to memory so va_arg can walk them like an array. Floating-point variadic arguments go in integer registers or on the stack even with a hardware FPU (the variadic calling convention is the soft-float one).

Embedded notes: a full printf implementation can add 10–30 KB of flash; small projects use newlib-nano (--specs=nano.specs), a minimal printf, or deferred/binary logging where the device sends a format ID and raw arguments and a PC tool formats them (Trice, defmt, Zephyr dictionary logging). Avoid printf in ISRs (slow and usually not reentrant).