Loading...

C essentialsAdvanced Topics

Variadic functions

8 min lesson

Next
  • A variadic function accepts a variable number of arguments, like printf does, using the ... syntax in its parameter list.
  • This matters because some functions need to accept any number of values: printing, logging, summing, or building formatted strings.
  • Think of a variadic function as a buffet plate: the cook hands you a plate and you choose how many items to put on it. The first item (or a count) tells the server how many more to expect.
  • The ellipsis ... in the parameter list marks the start of the extra arguments: int sum(int count, ...).
  • The va_list type, with va_start, va_arg and va_end from stdarg.h, gives you a way to read the extra arguments one by one.
  • The caller and the function must agree on how many arguments were passed and what type each is, because the compiler cannot check.
  • The computer reads the arguments from a special area based on the types you request with va_arg; wrong types give garbage.
  • The syntax is: #include <stdarg.h>; va_list ap; va_start(ap, lastNamed); then va_arg(ap, type); and va_end(ap);.
  • A realistic use: a logging function that takes a format string plus values, or a sum function that takes a count and then that many ints.
  • A surprising detail: you must call va_end before returning, and you need some way to know when to stop (a count or a sentinel like NULL).
  • The example program defines a sum function that takes a count followed by that many ints, and a printAll function that stops at a negative sentinel.
Keep in mind
  • Always include stdarg.h and call va_start and va_end correctly.
  • Provide a count or sentinel so the function knows when the arguments end.
  • The compiler cannot type-check variadic arguments; document the expected types.
  • Prefer variadic functions only when the flexibility is truly needed.
  • You now understand the machinery behind printf. Excellent work!
main.c
#include <stdio.h>
#include <stdarg.h>

// Sum a fixed count of int arguments
int sum(int count, ...) {
    // Prepare to read the extra arguments
    va_list ap;
    va_start(ap, count);
    int total = 0;
    // Read exactly count ints
    for (int i = 0; i < count; i++) {
        total += va_arg(ap, int);
    }
    // Always clean up
    va_end(ap);
    return total;
}

// Print ints until a negative sentinel is reached
void printAll(int first, ...) {
    va_list ap;
    va_start(ap, first);
    // Handle the first argument separately
    int value = first;
    while (value >= 0) {
        printf("%d ", value);
        value = va_arg(ap, int);
    }
    printf("\n");
    va_end(ap);
}

int main(void) {
    // Pass a count and exactly that many values
    printf("Sum: %d\n", sum(3, 10, 20, 30));
    // Pass values ending with -1 as the sentinel
    printAll(5, 10, 15, -1);
    return 0;
}

What happens: Sum: 60 5 10 15

Breaking it down

Ellipsis parameter

int sum(int count, ...)

The ... means the function accepts any number of extra arguments after count. The named parameter is required.

va_start

va_start(ap, count);

Initializes the va_list so it points to the first extra argument. The last named parameter is passed so the macro knows where to begin.

va_arg

va_arg(ap, int)

Reads the next argument as an int and advances the list. If the actual argument is a different type, the result is garbage.

va_end

va_end(ap);

Cleans up the va_list. It must be called before the function returns, or behavior is undefined.

Sentinel loop

while (value >= 0) { ... value = va_arg(ap, int); }

Reads until a negative value marks the end. Without a sentinel or count, the function cannot know when to stop.

Variadic macros

MacroPurposeExample
va_listHolds argument stateva_list ap;
va_startBegin readingva_start(ap, last)
va_argRead next valueva_arg(ap, int)
va_endFinish readingva_end(ap)
va_copyCopy the listva_copy(dst, src)

A helpful analogy

A variadic function is like a buffet plate: the cook hands you a plate (the function), and you choose how many items to put on it. The first item or a count tells the server how many more to expect. If you put more items than you announced, the server reads past the plate and picks up nonsense.

Nesting rules

  • 1.Always call va_start and va_end in the same function, with va_end before every return.
  • 2.Pass the last named parameter to va_start so the macro can find the extra arguments.
  • 3.Provide a count or a sentinel so the function knows when to stop reading.
  • 4.Document the expected types of the variadic arguments; the compiler cannot check them.

Common mistakes

Forgetting va_end

Avoid

va_start(ap, n); return total; // no va_end

Use instead

va_start(ap, n); va_end(ap); return total;

Skipping va_end is undefined behavior and can leak resources on some platforms.

Reading more arguments than were passed

Avoid

sum(2, 1, 2, 3, 4); // extra args ignored by sum

Use instead

sum(4, 1, 2, 3, 4);

The function reads exactly count values. Extra arguments are ignored, and too few cause it to read garbage.

Using the wrong type in va_arg

Avoid

va_arg(ap, double) for an int argument

Use instead

va_arg(ap, int)

va_arg must match the actual argument type. A mismatch reads the wrong bytes and gives garbage or crashes.

Quick tips

  • •Add a count or sentinel to every variadic function you write.
  • •Use printf-style format strings and vprintf to build flexible loggers.
  • •Test with zero extra arguments to make sure the function handles that case.
  • •Try changing the sentinel from -1 to another negative value in the example.
  • •Read the stdarg.h documentation once; the four macros are the whole story.
Previous
Next