Search code examples
cvariadic-functions

Use a vararg function in a vararg function


I want to call a variadic function in a variadic function. The code does not give an error, but the resulting values are incorrect. What is the correct way to do this?

#include <stdarg.h>

void SecondFunction (int count, ...) {
    va_list args;
    va_start(args, count);
    AddValues(count, args);
    va_end(args);
};

void AddValues(int count, ...) {
   va_list args;
   va_start(args, count);

   for(int i=count; i--; )
      processItem(va_arg(args, void*));

   va_end(args);
}

Solution

  • This will not work, but you can create a similar function that uses a va_list argument. That is exactly why functions such as vsyslog and vprintf exists. In its simplest form:

    void vAddValues(int count, va_list args) {
        int i;
        for (i = count; i--; )
            processItem(va_arg(args, void *));
    }