Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 135 ยท Functions

Variadic Functions

Write C functions that take any number of arguments with stdarg.h. Learn va_list, va_start, va_arg, va_copy and va_end, build a mini printf, and avoid the traps.

Most functions take a fixed list of parameters. printf doesn't: you can call it with one argument, or with twenty. Functions like this are called variadic functions, and C lets you write your own with three dots (...) in the parameter list and a handful of macros from <stdarg.h>.

Variadic functions are powerful but completely unchecked. The compiler doesn't know how many extra arguments arrived or what their types are, so your function has to find out on its own, and a mistake is undefined behavior rather than a compile error. In this lesson you'll learn how the machinery works, the three standard ways a variadic function learns how many arguments it got, how to forward arguments to vprintf and friends, and the rules that keep these functions safe.

Declaring a variadic function

You write ... as the last item in the parameter list. Everything before it is a normal named parameter:

C
int sum_ints(int count, ...);
void log_message(const char *format, ...);

Inside the function, you walk through the extra arguments with four macros from <stdarg.h>:

Macro What it does
va_list ap; declares a variable that tracks your position in the argument list
va_start(ap, last) starts the walk; last is the last named parameter
va_arg(ap, type) returns the next argument, which you claim has type type
va_end(ap) ends the walk; call it before the function returns
va_copy(dest, src) (C99) makes an independent copy of a position

Here is the classic first example: a function whose first argument says how many numbers follow.

C Summing a counted list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 60, 15 and 0. Notice what the function doesn't know: nothing stops a caller from writing sum_ints(4, 10, 20). The fourth va_arg would then read whatever happens to be in memory, which is undefined behavior. The count is a promise the caller makes, and the compiler can't check it.

C23 change: before C23, a variadic function needed at least one named parameter, and va_start took two arguments. C23 allows int f(...) with no named parameters and makes the second argument of va_start optional, so va_start(ap) works. Code that must compile as C17 or older should keep a named parameter and pass it to va_start.

How does the function know when to stop?

Since the language gives the function no count, every variadic function uses one of three conventions. Pick one and document it.

  1. An explicit count, as in sum_ints(3, ...). Simple and clear, but easy to get out of sync when someone adds an argument and forgets to update the number.
  2. A sentinel value that marks the end, such as a null pointer after a list of strings, or -1 after a list of non-negative numbers. The sentinel can't be a legal value.
  3. A format string that describes every argument, like printf's "%d %s". The most flexible option: it carries both the count and the types.

A sentinel works well for lists of pointers. This function joins any number of words and stops at a null pointer:

C A null pointer as the sentinel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is red, green, blue, then parse -> check -> compile -> link, then an empty line.

Why the cast in (char *)NULL? NULL may be defined as a plain 0, an int. In a normal call, the prototype converts it to a pointer for you, but in the ... part there's no parameter type to convert to, so an int zero would be passed where the function reads a pointer. On 64-bit systems an int is 4 bytes and a pointer is 8, so the read can pick up garbage. The cast makes the argument a real pointer. In C23 you can also pass nullptr, which always has pointer size.

Default argument promotions

Arguments in the ... part go through the default argument promotions before the call:

  • char, signed char, unsigned char, short and unsigned short become int (or unsigned int in rare cases where int can't hold every value).
  • bool becomes int.
  • float becomes double.

So the function never receives a char or a float. You must ask va_arg for the promoted type: va_arg(ap, int) for characters and small integers, va_arg(ap, double) for floats. Asking for char or float is undefined behavior, and GCC is blunt about it:

C
char c = va_arg(ap, char);   // WRONG: char arrives as int
TEXT
main.c:8:25: warning: 'char' is promoted to 'int' when passed through '...'
main.c:8:25: note: (so you should pass 'int' not 'char' to 'va_arg')
main.c:8:25: note: if this code is reached, the program will abort

GCC really does insert a trap instruction there, so the program crashes as soon as that line runs. Write char c = (char)va_arg(ap, int); instead. This promotion rule is also why printf uses the same %f for float and double: by the time printf sees the value, it's always a double.

Building a mini printf

A format string is the most capable convention, so let's write a tiny version of printf. It understands %d, %c, %s, %f and %%, and prints everything else as is.

C mini_printf with a format string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints:

TEXT
Order #1042 for Dana
Grade: A, discount: 15%
Total: 13.50 EUR
Unknown %q stays as is

Look at how %c and %f read their arguments: int and double, never char and float. The real printf works the same way, with many more cases (widths, precision, l and ll length modifiers, and so on). It also shows the weakness of the design: if the format says %d but the caller passes a double, the function reads the wrong bytes. The real printf can't detect that either. Only the compiler can, and only because it knows printf's rules, as you'll see below.

Forwarding arguments: vprintf and friends

Often you want a function that adds something (a prefix, a timestamp, a log level) and then formats like printf. You can't pass ... on to another variadic function directly. Instead, the standard library offers a v version of each formatting function that takes a va_list:

Variadic Takes a va_list
printf vprintf
fprintf vfprintf
snprintf vsnprintf
scanf, sscanf vscanf, vsscanf

The pattern is always the same: va_start, call the v function, va_end.

C A logger built on vfprintf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is:

TEXT
[INFO] server started on port 8080
[WARN] disk /dev/sda1 is 91.2% full
[INFO] created 'invoice-0037'

(91.25 prints as 91.2: the value lies exactly halfway between 91.2 and 91.3, and glibc's printf rounds such ties to the even digit.)

Two details matter here:

  • A va_list can only be walked once. After vsnprintf has read the arguments, ap is used up. format_new needs two passes (measure, then write), so it makes a copy with va_copy first. Every va_copy needs its own va_end.
  • __attribute__((format(printf, 2, 3))) is a GCC and Clang extension. It says "parameter 2 is a printf-style format, and the variable arguments start at parameter 3". With it, -Wall checks calls to log_at exactly like calls to printf, so log_at("INFO", "%d", 3.5) gets a warning. It's the single best way to make a variadic wrapper safe. MSVC doesn't support it; portable code hides it behind a macro.

Rules and pitfalls

Variadic functions trade safety for flexibility. Keep these rules in mind:

  • Types are never checked. If the caller passes a long and you read an int, or pass an int and you read a double, the behavior is undefined. Be especially careful with size_t and long values, and with literals: 3 is an int, 3.0 is a double, 3L is a long.
  • Ask for promoted types: int for anything smaller, double for float.
  • Every va_start and va_copy needs a matching va_end in the same function, before it returns.
  • Don't read past the end. There's no way to ask "are there more arguments?". Your count, sentinel or format must be correct.
  • Cast null-pointer sentinels: (char *)NULL, or nullptr in C23.
  • You can't pass ... along, only a va_list to a v function. Write a v version of your own functions (taking va_list) if other code needs to forward to them.
  • Prefer a fixed signature when you can. If a function always takes "some ints", an array and a length (int sum(const int *values, size_t count)) is checked by the compiler and just as easy to call. Arrays shows how to pass them.

A macro can count arguments for you. #define SUM(...) sum_array((int[]){__VA_ARGS__}, sizeof((int[]){__VA_ARGS__}) / sizeof(int)) builds a compound-literal array from the arguments, so the count is always right and every value is converted to int. The Macros lesson covers __VA_ARGS__ and its tricks.

Variadic functions shine for formatting and logging, where a format string carries the types. For most other jobs, a plain array parameter or a struct of options is the safer design.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a variadic function, a caller passes 'z' in the ... part. Which call reads it correctly?

    Character arguments are promoted to int when passed through the variable part, so you must read an int (and convert it to char if you like). Reading a char is undefined behavior; GCC even inserts a trap.
  2. 2. What does sum_ints(2, 10, 20, 30) return, using the sum_ints function from this lesson?

    The count says 2, so the function reads only 10 and 20 and returns 30. The extra 30 is passed but never read, which is harmless. Reading more arguments than were passed would be undefined behavior.
  3. 3. Why does format_new call va_copy before calling vsnprintf twice?

    After vsnprintf reads the arguments through ap, ap can't be reused. va_copy saves an independent starting position for the second pass, and it needs its own va_end.
  4. 4. Why should a null-pointer sentinel be written as (char *)NULL rather than plain NULL?

    Without a parameter type, an int 0 stays an int, which may be smaller than a pointer. The function reads a pointer and may get garbage. A cast (or C23 nullptr) passes a real null pointer.
  5. 5. What does the GCC attribute format(printf, 2, 3) on a logging function give you?

    The attribute tells the compiler that parameter 2 is a printf-style format and arguments start at 3, so -Wall warns about mismatches. It changes nothing at run time.

Summary

  • A variadic function ends its parameter list with ...; use va_list, va_start, va_arg and va_end from <stdarg.h> to read the extra arguments.
  • The function must learn the count and types itself: an explicit count, a sentinel value, or a format string.
  • Extra arguments are promoted: small integers and char become int, float becomes double. Always ask va_arg for the promoted type.
  • Reading the wrong type or too many arguments is undefined behavior, and the compiler can't check it for you.
  • Forward arguments by passing a va_list to vprintf, vfprintf or vsnprintf; use va_copy when you need two passes.
  • Mark printf-style wrappers with __attribute__((format(printf, n, m))) on GCC/Clang so calls get checked.
  • C23 allows f(...) with no named parameter and va_start(ap) with one argument.

Next: inline Functions, where you'll see how C's inline keyword really works.