INTRODUCTION
A variadic function is a function that accepts an infinite number of arguments e.g printf() that can accept as many arguments as possible. ISO C defines a syntax for declaring a function to take a variable number or type of arguments. (Such functions are referred to as varargs functions or variadic functions.) However, the language itself provides no mechanism for such functions to access their non-required arguments; instead, you use the variable arguments macros defined in <stdarg.h>
.
LIST OF MACROS USED IN VARIADIC FUNCTION
MACRO | WHAT THEY DO |
va_list | It is a type defined in stdarg.h that is used to declare a variable that can hold the information needed by the macros va_start, va_arg, and va_end. |
va_start | Initializes the arguments. |
va_arg | retrieves the arguments. |
va_end | Cleans up the argument list. |
let's look at a simple function that finds the sum of all the arguments passed to it and outputs the result.
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...);
int main(void)
{
int result;
result = sum(3, 1, 3, 4);
printf("%d\n", result);
return (0);
}
int sum(int count, ...)
{
va_list args;
va_start(args, count) ;
int s = 0;
int i;
for (i = 0; i < count; i++)
{
int x = va_arg(args, int);
s += x;
va_end(args);
}
}
In the example above, the variadic function sum(int count, ...)
, takes two arguments one of which is a list of arguments ...
, int count
is the number of arguments present in the list of arguments.
WHAT IS THE NEED FOR VARIADIC FUNCTIONS
Variadic functions are used in mathematics and computer programming. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed. Some use cases of variadic functions include:
Summing of numbers.
Concatenating strings.
When the number of input params is unknown or will vary when called.
To make your code more readable.
Creating functions similar to
printf()
function.They are useful in system programming due to their flexibility in the size of the list of input arguments
In summary, variadic functions is a useful technical in mathematical and computing process for real life problems like creating a simple calculator app that adds up all the numbers passed to it. Other functions similar to printf()
are created using variadic function.