How variadic functions are used in C

A variadic function is a function that accepts any number of arguments. In most cases the number of arguments the function may take is unknown.

Syntax:

A variadic function follows the following syntax:

int func(const char *a, const int b, ...);

The use of const is used to indicate fixed arguments and the use of ... indicates the possibility of any number of additional arguments.

Receiving argument values

To access optional arguments in order you can follow the following steps:

  1. Initialize an argument pointer variable of type va_list using va_start. The argument pointer when initialized points to the first optional argument.

  2. Make successive calls to va_arg. to access the additional arguments.

  3. To show that you are done with the argument pointer variable call va_end.

Example:

The following function is an example of a variadic function that returns the sum of all its parameters:

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

/**
 * sum_all - sum of all its parameters
 * @n: The first operand
 * @...: additional args
 *
 * Return: sum of integers
 */
int sum_all(const unsigned int n, ...)
{
    unsigned int i, sum;

    /* Initialize the argument list. */
    va_list ap;

    if (n == 0)
        return (0);

    va_start(ap, n);

    sum = 0;
    for (i = 0; i < n; i++)
     /* Get the next argument value. */
        sum += va_arg(ap, int);

    /* Clean up. */
    va_end(ap);
    return (sum);
}
/**
 * main - check the code
 *
 * Return: Always 0.
 */
int main(void)
{
    int sum;

    sum = sum_all(2, 3, 5);
    printf("%d\n", sum);
    sum = sum_all(8, 13, 21, 34, 55);
    printf("%d\n", sum);    
    return (0);
}

Output:

8
1805159931

Note: Each call to va_start and va_copy must be matched by a corresponding call to va_end. stdarg.h header allows functions to receives any number of positional arguments.

Variadic functions must have at least one named parameter.

printf function is a good example of a use case of variadic functions. Variadic functions are useful when a function accepts any number of arguments.

Further reading:

stdarg.h

Variadic functions

Const keyword

Happy coding!