How to Use stdarg.h in C for Variable Arguments
In C, you use
stdarg.h to create functions that accept a variable number of arguments. This involves using va_list to declare a list, va_start to initialize it, va_arg to access each argument, and va_end to clean up.Syntax
To use variable arguments in a function, include stdarg.h and follow this pattern:
va_list args;declares a variable to hold the arguments.va_start(args, last_fixed_param);initializes the list, wherelast_fixed_paramis the last named parameter before the variable ones.va_arg(args, type)retrieves the next argument of the specifiedtype.va_end(args);cleans up the list when done.
c
#include <stdarg.h> void example_function(int fixed_param, ...){ va_list args; va_start(args, fixed_param); // use va_arg to access arguments va_end(args); }
Example
This example shows a function sum that adds a variable number of integers. The first parameter tells how many numbers follow.
c
#include <stdio.h> #include <stdarg.h> int sum(int count, ...){ va_list args; va_start(args, count); int total = 0; 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
Common mistakes when using stdarg.h include:
- Not calling
va_endafter finishing with arguments, which can cause undefined behavior. - Using the wrong type in
va_arg, leading to incorrect values or crashes. - Not knowing how many arguments were passed, which requires a fixed parameter to indicate count or a sentinel value.
c
/* Wrong: Missing va_end */ #include <stdarg.h> void wrong_function(int count, ...){ va_list args; va_start(args, count); int val = va_arg(args, int); // forgot va_end(args); } /* Correct: Always call va_end */ void correct_function(int count, ...){ va_list args; va_start(args, count); int val = va_arg(args, int); va_end(args); }
Quick Reference
| Function | Purpose |
|---|---|
| va_list | Type to hold variable argument list |
| va_start(args, last_fixed) | Initialize args to start after last fixed parameter |
| va_arg(args, type) | Retrieve next argument of given type |
| va_end(args) | Clean up the argument list |
Key Takeaways
Use stdarg.h to handle functions with variable numbers of arguments in C.
Always initialize with va_start and clean up with va_end to avoid errors.
Use va_arg with the correct type to safely access each argument.
Include a fixed parameter to know how many variable arguments to expect.
Common mistakes include missing va_end and wrong argument types.