Variable Arguments
Sometimes, you may encounter situations where you want a function to take a variable number of arguments instead of a predefined number of arguments. C provides a solution for this by allowing you to define a function that can accept a variable number of arguments based on specific needs. The following example demonstrates the definition of such a function.
int func(int, ... )
{
.
.
.
}
int main()
{
func(2, 2, 3);
func(3, 2, 3, 4);
}
Note that the last parameter of the function func() is written as an ellipsis, which is three dots (...), and the parameter before the ellipsis is an int, representing the total number of variable arguments to be passed. To use this feature, you need to include the stdarg.h header file, which provides functions and macros to implement variable arguments. The specific steps are as follows:
- Define a function with the last parameter as an ellipsis, and you can set custom parameters before the ellipsis.
- In the function definition, create a variable of type va_list, which is defined in the stdarg.h header file.
- Use the int parameter and the vastart macro to initialize the valist variable to a list of arguments. The va_start macro is defined in the stdarg.h header file.
- Use the vaarg macro and the valist variable to access each item in the argument list.
- Use the vaend macro to clean up the memory allocated to the valist variable.
Now, let's write a function with a variable number of arguments and return their average, following the steps above:
Example
#include <stdio.h>
#include <stdarg.h>
double average(int num,...)
{
va_list valist;
double sum = 0.0;
int i;
/* Initialize valist for num number of arguments */
va_start(valist, num);
/* Access all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* Clean up the memory reserved for valist */
va_end(valist);
return sum/num;
}
int main()
{
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be noted that the function average() is called twice, and each time the first parameter indicates the total number of variable arguments being passed. The ellipsis is used to pass a variable number of arguments.
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000