Variadic Functions in C

Our first example demonstrates a variadic function. Variadic functions can be called with any number of trailing arguments. For example, printf is a common variadic function in C.

Here’s a function that will take an arbitrary number of ints as arguments:

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

void sum(int count, ...) {
    va_list args;
    va_start(args, count);

    printf("[ ");
    int total = 0;
    for (int i = 0; i < count; i++) {
        int num = va_arg(args, int);
        printf("%d ", num);
        total += num;
    }
    printf("] ");

    printf("%d\n", total);

    va_end(args);
}

Within the function, we use the va_list, va_start, and va_arg macros to handle the variable arguments. We can iterate over the arguments and perform operations on them.

int main() {
    // Variadic functions can be called with individual arguments.
    sum(2, 1, 2);
    sum(3, 1, 2, 3);

    // If you already have multiple args in an array,
    // you need to call the function for each element individually.
    int nums[] = {1, 2, 3, 4};
    sum(4, nums[0], nums[1], nums[2], nums[3]);

    return 0;
}

When you run this program, you’ll see:

$ gcc variadic_functions.c -o variadic_functions
$ ./variadic_functions
[ 1 2 ] 3
[ 1 2 3 ] 6
[ 1 2 3 4 ] 10

In C, variadic functions are implemented using the <stdarg.h> header, which provides macros for accessing the variable arguments. Unlike some other languages, C doesn’t have a built-in way to pass an array directly to a variadic function, so we have to pass the elements individually.

Another key aspect of functions in C is their ability to use function pointers, which we’ll look at next.