Variable arguments in C
Posted by tread on February 20, 2007
Another area that I never really looked into is how to accept variable arguments in C. This time, the tutorial I am using is here.
What it boils down to is:
#include <stdargs.h> // include stdargs to use the macros va_*
int sum(int n, …) // n is the first argument, and denotes number of arguments
{
va_list args; // args here will store the list of arguments
int sum = 0, i = 0;
va_start (args, n); // initialize args – pass args and n to va_start
for (i = 0; i < n; i++) // loop n times – number of arguments
sum += va_arg (args, int); // va_arg () will return the argument – give it the initialized args and the type (int)
va_end (args); // end processing the argument list.
return sum;
}
That’s about it.
You can call this as
x = sum (5, 1, 2, 3, 4, 5) ;
or
x = sum (2, 100, 200);
Kranti Kumar said
the way u explained this topic is very easy to understand and useful. previously i read about variable arguments list so many times but i couldn’t grasp good. but by this example i got the point right. Thank U very much.
tread said
You’re welcome!
Dan said
How do you pass a variable argument on to another function? If I have a macro that is used to log data and it’s of the format of
LOG(DEBUG,format, params);
void logger(int messageType, char *format, …)
{
printf(format, …); // this is what I’m wondering, how do I pass the va args on?
vasanth said
use vprintf and pass the va_list.