Variadic functions are functions that can take a variable number of arguments. 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. The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter.
Syntax:
int function_name(data_type variable_name, ...);
Values of the passed arguments can be accessed through the header file named as:
#include <stdarg.h>
<stdarg.h> includes the following methods:
Methods
|
Description
|
va_start(va_list ap, argN) |
This enables access to variadic function arguments.
where *va_list* will be the pointer to the last fixed argument in the variadic function
*argN* is the last fixed argument in the variadic function.
From the above variadic function (function_name (data_type variable_name, …);), variable_name is the last fixed argument making it the argN. Whereas *va_list ap* will be a pointer to argN (variable_name)
|
va_arg(va_list ap, type) |
This one accesses the next variadic function argument.
*va_list ap* is the same as above i.e a pointer to argN
*type* indicates the data type the *va_list ap* should expect (double, float, int etc.)
|
va_copy(va_list dest, va_list src) |
This makes a copy of the variadic function arguments. |
va_end(va_list ap) |
This ends the traversal of the variadic function arguments. |
Here, va_list holds the information needed by va_start, va_arg, va_end, and va_copy.
Program 1:
The following simple C program will demonstrate the working of the variadic function AddNumbers():
C
#include <stdarg.h>
#include <stdio.h>
int AddNumbers( int n, ...)
{
int Sum = 0;
va_list ptr;
va_start (ptr, n);
for ( int i = 0; i < n; i++)
Sum += va_arg (ptr, int );
va_end (ptr);
return Sum;
}
int main()
{
printf ( "\n\n Variadic functions: \n" );
printf ( "\n 1 + 2 = %d " ,
AddNumbers(2, 1, 2));
printf ( "\n 3 + 4 + 5 = %d " ,
AddNumbers(3, 3, 4, 5));
printf ( "\n 6 + 7 + 8 + 9 = %d " ,
AddNumbers(4, 6, 7, 8, 9));
printf ( "\n" );
return 0;
}
|
Output:
Variadic functions:
1 + 2 = 3
3 + 4 + 5 = 12
6 + 7 + 8 + 9 = 30
Program 2: Below is the C program consisting of the variadic function LargestNumber():
C
#include <stdarg.h>
#include <stdio.h>
int LargestNumber( int n, ...)
{
va_list ptr;
va_start (ptr, n);
int max = va_arg (ptr, int );
for ( int i = 0; i < n-1; i++) {
int temp = va_arg (ptr, int );
max = temp > max ? temp : max;
}
va_end (ptr);
return max;
}
int main()
{
printf ( "\n\n Variadic functions: \n" );
printf ( "\n %d " ,
LargestNumber(2, 1, 2));
printf ( "\n %d " ,
LargestNumber(3, 3, 4, 5));
printf ( "\n %d " ,
LargestNumber(4, 6, 7, 8, 9));
printf ( "\n" );
return 0;
}
|
Output:
Variadic functions:
2
5
9