C - Variable Length Number of Arguments
In C programming, you can work with a variable number of arguments in a function using ellipsis (...
) and the <stdarg.h>
library. This feature allows you to create functions that can accept different numbers of arguments at runtime. Such functions are commonly referred to as variadic functions.
Example:
#include <stdio.h>
#include <stdarg.h>
// A variadic function that calculates the sum of its arguments
int sum(int count, ...) {
int result = 0;
// Declare a va_list to hold the variable arguments
va_list args;
// Initialize the va_list with the variable arguments
va_start(args, count);
// Iterate through the arguments and calculate the sum
for (int i = 0; i < count; i++) {
int num = va_arg(args, int); // Get the next argument
result += num;
}
// Clean up the va_list
va_end(args);
return result;
}
int main() {
int total1 = sum(3, 10, 20, 30); // Sum of three integers
int total2 = sum(4, 5, 15, 25, 35); // Sum of four integers
printf("Total 1: %d\n", total1);
printf("Total 2: %d\n", total2);
return 0;
}
In this example:
- The
sum
function accepts a variable number of integer arguments. The first argument, count
, specifies the number of arguments that follow.
- Inside the
sum
function, a va_list
object (args
) is declared to hold the variable arguments.
- The
va_start
macro initializes the va_list
with the variable arguments.
- A loop iterates through the arguments, and
va_arg
retrieves each argument.
- After processing the arguments, the
va_end
macro cleans up the va_list
.
When you call sum
with a specified number of arguments, it calculates the sum of those arguments. The function is flexible and can handle a different number of arguments each time it's called.
Output:
Total 1: 60
Total 2: 80
Variadic functions are commonly used in C for functions like printf
and scanf
, which accept a variable number of arguments for formatting and parsing. They provide flexibility and convenience when designing functions that need to work with different numbers of inputs.