How to Use Variable Arguments in C: Syntax and Example
In C, you use variable arguments by including
<stdarg.h> and defining a function with an ellipsis ... in its parameters. Use va_start, va_arg, and va_end macros to access the extra arguments inside the function.Syntax
To define a function that accepts variable arguments, use an ellipsis ... after fixed parameters. Inside the function, use va_list to declare a variable for argument access. Then use va_start to initialize it, va_arg to retrieve each argument, and va_end to clean up.
Example syntax:
void functionName(type fixedArg, ...) {
va_list args;
va_start(args, fixedArg);
// Access arguments with va_arg
va_end(args);
}c
void functionName(type fixedArg, ...) { va_list args; va_start(args, fixedArg); // Access arguments with va_arg va_end(args); }
Example
This example shows a function sum that takes a count of numbers followed by that many integers. It adds all the integers and returns the total.
c
#include <stdio.h> #include <stdarg.h> int sum(int count, ...) { va_list args; int total = 0; va_start(args, count); for (int i = 0; i < count; i++) { total += va_arg(args, int); } va_end(args); return total; } int main() { int result = sum(4, 10, 20, 30, 40); printf("Sum is %d\n", result); return 0; }
Output
Sum is 100
Common Pitfalls
- Not calling
va_endafter finishing argument access can cause undefined behavior. - Using
va_argwith the wrong type leads to incorrect values or crashes. - Forgetting to pass the fixed argument before
...in the call makesva_startfail. - Variable arguments do not have type safety, so be careful to know the types and count.
c
#include <stdarg.h> #include <stdio.h> // Wrong: missing va_end int wrong_sum(int count, ...) { va_list args; int total = 0; va_start(args, count); for (int i = 0; i < count; i++) { total += va_arg(args, int); } // va_end(args); // Missing cleanup return total; } // Correct usage int correct_sum(int count, ...) { va_list args; int total = 0; va_start(args, count); for (int i = 0; i < count; i++) { total += va_arg(args, int); } va_end(args); return total; }
Quick Reference
| Macro | Purpose |
|---|---|
| va_list | Type to hold variable argument list |
| va_start(args, last_fixed_arg) | Initialize args to start after last fixed argument |
| va_arg(args, type) | Retrieve next argument of given type |
| va_end(args) | Clean up the argument list |
Key Takeaways
Use macros va_start, va_arg, and va_end to handle variable arguments in C.
Always call va_end after finishing to avoid undefined behavior.
Know the number and types of arguments to safely retrieve them with va_arg.
Variable arguments lack type checking, so use carefully with fixed parameters indicating count or types.