Functions with unknown arguments
What you'll learn: How to create flexible functions that accept a varying number of arguments using the stdarg.h library.
The "Open Invitation" Function
Normally, C is very strict. If you define a function to take two integers, you must provide exactly two integers. But think about the printf() function: sometimes you pass it one argument, and sometimes ten. This is called a variadic function.
Think of it like a dinner party where you don't know exactly how many guests are coming. You know there will be at least one person (the host), but they might bring three friends or twelve. To handle this in C, we use a special ellipsis (...) syntax and the toolset provided by the <stdarg.h> header.
How it works
To build a variadic function, you need at least one "fixed" argument first. This acts as the anchor. After that, you use three dots ... to tell C, "more stuff is coming, but I don't know how much yet."
Inside the function, you use a "pointer-like" object called a va_list to step through the hidden arguments one by one.
#include <stdio.h>
#include <stdarg.h>
// 'count' is our fixed argument so we know how many numbers to read
void print_sum(int count, ...) {
va_list args; // 1. Create a list to hold the arguments
va_start(args, count); // 2. Initialize the list starting after 'count'
int sum = 0;
for (int i = 0; i < count; i++) {
// 3. Grab the next 'int' from the list
sum += va_arg(args, int);
}
va_end(args); // 4. Clean up the list
printf("Total sum: %d\n", sum);
}
int main() {
print_sum(3, 10, 20, 30); // Sums 3 numbers
print_sum(5, 1, 2, 3, 4, 5); // Sums 5 numbers
return 0;
}
The Four Magic Macros
To navigate the unknown arguments, you must use these four tools from stdarg.h:
va_list: A special type that tracks where you are in the argument list.va_start: Plugs the list into the function and points it to the first optional argument.va_arg: The "grabber." You must tell it the type (likeintordouble) you expect to find next.va_end: The cleanup crew. Always call this before the function returns to prevent crashes.
Because the computer doesn't automatically know when the list ends, you usually need your "fixed" argument to tell the function how many items to expect, just like our count variable above.
Key takeaway
Variadic functions use ... and the stdarg.h library to accept any number of arguments, provided you have at least one fixed parameter to start the process.