Variadic arguments is the term used to refer to the arguments of a variadic function.
A variadic function is one that takes a variable number of arguments. A common example is the printf()
function defined in the <stdio.h>
header.
The declaration of a variadic function uses ellipses as the last parameter.
The prototype for the printf()
function is as follows:
int printf(const char* format, ...);
To access variadic arguments, we must include the <stdarg.h>
header.
We use the following library facilities:
Facility | Use |
va_start | start access to variadic arguments |
va_arg | access the next variadic argument |
va_copy | makes a copy of the variadic arguments |
va_end | end traversal of variadic arguments |
va_list | holds information needed by other facilities |
#include <stdio.h>#include <stdarg.h>int variadic_addition (int count,...){va_list args;int i, sum;va_start (args, count); /* Save arguments in list. */sum = 0;for (i = 0; i < count; i++)sum += va_arg (args, int); /* Get the next argument value. */va_end (args); /* Stop traversal. */return sum;}int main(){// call 1: 4 argumentsprintf("Sum: %d\n", variadic_addition(3, 10, 20, 30));//call 2: 6 argumentsprintf("Sum: %d\n", variadic_addition(5, 10, 20, 30, 40, 50));return 0;}
variadic_addition()
adds all the variadic arguments and returns the sum.
This function is able to process both calls that were made, each with a different number of arguments.
Free Resources