Variable argument lists in C

This explains how to create a function in C that has a variable number of arguments passed to it.

In C it is possible to create a function that will accept a variable amount of arguments. The parameter must have at least one defined parameter followed by an ellipsis, three periods “…”. For example printf()’s prototype has one defined parameter and an ellipses:

printf(char *, …);

However, just an ellipses is not allowed:

function(…);

You may use as many defined arguments as you would like, but the ellipses must be the last, for example:

function(int, char *, float, …);

There are several functions used to access the arguments passed through the ellipses, to use them you must include cstdarg.

#include 

Note that cstdarg is not a header file, but it is included like one.

In the function that is receiving the variable arguments you must have a va_list variable that is used by the functions that retrieve the arguments passed through the ellipses. The function va_start() will setup the va_list variable so you can retrieve arguments. The va_start() function takes two arguments. The first is the va_list variable, and the second is the argument that immediately precedes the variable arguments.

The function used to actually retrieve the arguments is va_arg(). This function also takes two arguments. The first is a va_list variable that has previously established with va_start(), and the second is the type of variable you want to retrieve. For the type you use any variable type; for example int or char. The va_arg() function will return the value of the variable you are retrieving.

When you are done you must call va_end() to clean up the va_list variable. It only takes a va_list variable.

Here is an example of all that put together:

#include
#include

void VarArg(int Num, …);

void main(void)
{
     VarArg(4, 1, 2, 3, 4);
     VarArg(3, 6, 7, 8);

     return;
}

void VarArg(int Num, …)
{
     va_list VList;
     va_start(VList, Num);

     printf(“\nPassed parameters: “);

     for (; Num > 0; Num–)
     {
          printf(“ %d,”, va_arg(VList, int);
     }

     va_end(VList);
     return;
}

Leave a Reply

© 2007 Mindlence