Variable arguments in C

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);

Advertisements

4 thoughts on “Variable arguments in C

  1. 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.

  2. 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?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s