Variadic Functions

1-minute read

These are functions which accept a variable number of arguments. printf and scanf are variadic functions. These functions are most useful if we do not know how many values will be passed to the function at compile time.

We use the stdarg.h header file to access the macros and functions needed to meaningfully interact with variadic functions.

Here is an example of a function used to find the sum of its arguments:

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

void sum(int n,...){
    va_list args;
    va_start(args,n);
    int total = 0;
    printf("The sum of the numbers ");
    for (int i=0;i<n;i++){
        int current_num = va_arg(args,int);
        if (i==n-1){
            printf("and %d ",current_num);
        }else{
            printf("%d ",current_num);
        }
        total+=current_num;
    }
    va_end(args);
    printf("is %d\n",total);
}

int main(void){
    sum(3,1,2,3);
    sum(4,1,2,3,9);
    return 0;
}
variadic-sum-function.c
Copy

We use the va_start macro in order to tell the computer where the first argument in the variable argument list is. The va_list datatype is used to store a list of variable arguments. The va_end macro cleans up the va_list.


Support us via BuyMeACoffee

Resources

Here are some resources we recommend for you to use along with this lesson: