c programming tips and tricks

Variable-length argument lists

Normally you declare a function to take a fixed number of arguments. But it is also possible to define functions capable of taking variable numbers of arguments. The standard C function printf() is a function of this sort. You can put almost any number of integers, floats, doubles, and strings in the format specifier part (after the string argument), and the printf() function will figure out what to do with them. Just like printf(), you can declare your own functions that contain a variable number of arguments.

Here is an example:

int vararg(int arg_count, ...) {}

The first argument here, arg_count, is an integer that gives the actual number of arguments that follow it in the “variable” argument list, which is shown by the three dots.

There are a few built-in functions or macros that deal with variable arguments: va_list, va_start,va_arg, and va_end (these are defined in the stdarg.h header file).

First, you need to declare a pointer to the variable arguments:

va_list argp;

Next, set this argp variable to the first argument in the variable part. This is the argument after the last fixed argument; here arg_count:

va_start(argp, arg_count);

Then we can extract each variable argument one at a time from the variable part using va_arg:

for (i = 0; i < arg_count; i++) {
      j = va_arg(argp, int);
      t += j;

Note that you need to know in advance the type of the argument being retrieved (here it’s a simpleint) and the number of arguments (here, given by the fixed argument arg_count).

Finally, you need to tidy up by calling va_end:

Leave a Reply

Your email address will not be published. Required fields are marked *