Course contentsShow
← C
Lesson 372 of 1,2195. FunctionsFree lesson

The `stdarg.h` library

The stdarg.h library

What you'll learn: How to use the standard library tools that allow a single function to accept an unlimited number of arguments.

Standard C functions usually have a fixed "signature"—if you define a function with three integers, it must always take three integers. However, sometimes you need a function to be more flexible, like a chef who can handle a grocery bag regardless of whether it contains two apples or twenty oranges. To do this in C, we use variadic functions powered by the <stdarg.h> header.

The "Secret Sauce" Macros

To handle an unknown number of arguments, stdarg.h provides a specific type and three primary macros that act like a pointer moving through a list:

  1. va_list: Think of this as a bookmark. It keeps track of where you are in the list of arguments.
  2. va_start: This initializes your "bookmark." You tell it where the list begins by passing the name of the very last fixed (named) argument.
  3. va_arg: This fetches the next item. Because the computer doesn't know what data types are in the list, you must explicitly tell va_arg what type to expect (e.g., int or double).
  4. va_end: This cleans up the memory once you are finished.

Putting it into Practice

The most common way to use this is to pass a "count" as the first argument, so the function knows how many items follow.

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

// The "..." (ellipsis) tells C more arguments are coming
void print_sum(int count, ...) {
    va_list args;           // 1. Create the bookmark
    int sum = 0;

    va_start(args, count);  // 2. Start after the 'count' argument

    for (int i = 0; i < count; i++) {
        // 3. Fetch the next 'int' from the list
        sum += va_arg(args, int);
    }

    va_end(args);           // 4. Clean up
    printf("Total sum: %d\n", sum);
}

int main() {
    print_sum(3, 10, 20, 30);       // Works with 3 numbers
    print_sum(5, 1, 2, 3, 4, 5);    // Works with 5 numbers
    return 0;
}

Why it matters

Without stdarg.h, functions like printf() wouldn't be possible. printf uses a format string (like "%d %s") as its last fixed argument to figure out how many variables follow and what types they are. By mastering these macros, you gain the ability to write highly flexible tools that adapt to whatever data the user throws at them.

Key takeaway

Use va_list, va_start, va_arg, and va_end from <stdarg.h> to process functions with a variable number of arguments indicated by the ... ellipsis.