Variadic functions

suggest change

A variadic function accepts arguments beyond its named parameters. Declare it with an ellipsis and process the additional arguments using macros from <stdarg.h>.

#include <stdarg.h>
#include <stddef.h>

double sum(size_t count, ...)
{
    va_list arguments;
    va_start(arguments, count);

    double total = 0.0;
    for (size_t index = 0; index < count; ++index) {
        total += va_arg(arguments, double);
    }

    va_end(arguments);
    return total;
}

The function needs an external contract that specifies the number and types of arguments. In this example, count values of type double must follow. Passing fewer arguments or requesting a type incompatible with the promoted argument type causes undefined behavior.

Default argument promotions apply:

Consequently, retrieve a passed float as double, and retrieve most narrow integer values as int.

Each va_start or va_copy invocation must eventually be matched by va_end in the same function. Use va_copy before traversing a va_list independently; assigning one va_list to another is not portable.

va_list can be an array or another non-pointer representation. Pass it only in ways allowed by the API, and do not assume that a helper's traversal leaves the caller's copy unchanged.

Format strings, explicit counts, and sentinel values are common contracts for variadic functions. Prefer a typed interface when the set of arguments is known because the compiler can then check calls directly.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents