![]() |
VOOZH | about |
In C language, variadic functions are functions that can take a variable number of arguments. This feature is useful when the number of arguments for a function is unknown. It takes one fixed argument, and then any number of arguments can be passed.
Below is an example demonstrating how to print a variable number of arguments using a variadic function:
1 2 3 1 2 3 4 5
Explanation: In this example, the print() function takes a fixed first parameter n and the rest parameters vary. We have called this function with 1, 2, 3, 4, and 5 arguments and it was able to work for both.
A variadic function takes at least one fixed argument and an ellipsis(…) as the last parameter.
return_type name(fixed_arg, ...);
The above syntax allows users to pass the variable arguments, but to access the variable arguments inside the function, we have to use the methods specified in the <stdarg.h> library. The step-by-step process for this is as follows:
Use the va_list type to declare a variable that will store the information needed to retrieve the additional arguments.
va_list list;
This macro initializes the va_list to retrieve arguments from the variable arguments section.
va_start(list, fixed_arg);
where,
This macro returns the next argument from the list. It must be used repeatedly to access all arguments.
va_arg(list, type);
The number of times it should be called should not exceed the number of parameters passed. Due to this, the count of variable arguments passed is also passed as fixed parameters.
where,
Note: It is important to not mix up the type of the arguments.
Once all the arguments are processed, use va_end() to clean up the va_list. This ensures that resources associated with va_list are properly released.
va_end(list);
The below examples demonstrate the use of variadic functions in C language:
1 + 2 = 3 3 + 4 + 5 = 12 6 + 7 + 8 + 9 = 30
Explanation: The getSum() function calculates the sum of n variable arguments by iterating through the list of arguments and adding each one to a sum. It uses va_list, va_start, and va_arg to handle the variable arguments and returns the sum.
Integer: 10 Float: 3.14 Integer: 20 Float: 2.71
Explanation: In this example, print() takes an integer count as the first parameter, followed by a variable number of arguments. We use va_arg to print integers and floats alternately, based on their position in the argument list.