What Are Variadic Functions?
Variadic functions accept a variable number of arguments. You already use one every day —
printf:c
The
<stdarg.h> header provides the tools to write your own variadic functions.The stdarg.h API
| Macro | Purpose |
|---|---|
va_list | Type to hold variadic argument state |
va_start(ap, last_fixed) | Initialize the list after the last fixed parameter |
va_arg(ap, type) | Retrieve the next argument of the given type |
va_end(ap) | Clean up |
Basic Example: Sum of Integers
c
Critical: There is no way to know the number or types of variadic arguments automatically. You must communicate this through a fixed parameter (likecount) or a format string (likeprintfdoes).
Building a Custom Logger
c
Tip: Usevprintf,vfprintf, andvsprintfto forward variadic arguments to standard I/O functions. These accept ava_listinstead of....
Common Pitfalls
Wrong Type in va_arg
c
Forgetting va_end
Always call
va_end before the function returns. Skipping it can cause memory leaks or crashes on some platforms.Integer Promotion
Small types (
char, short) are automatically promoted to int when passed as variadic arguments. float is promoted to double.c
Sentinel-Terminated Variadic Functions
Instead of a count parameter, some functions use a sentinel value (like
NULL or -1) to mark the end:c
Summary
| Concept | Detail |
|---|---|
| Include | #include <stdarg.h> |
| Declare | At least one fixed param before ... |
| Initialize | va_start(args, last_fixed_param) |
| Read | va_arg(args, type) |
| Cleanup | va_end(args) |
| Forward | Use vprintf / vfprintf |
| Promotion | char → int, float → double |