2

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);
}
Meng
  • 191
  • 9
  • Looking at the way you're implementing this, I have a gut feeling that you are trying to use the feature for aesthetic reasons. – Cheatah May 06 '20 at 06:55

2 Answers2

5

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 *));
}
Cheatah
  • 1,825
  • 2
  • 13
  • 21
4

Read more carefully stdarg(3) or the C11 standard n1570 and documentation on variadic functions in C.

You need to use va_list and probably va_copy

Read also about the calling conventions of your particular C implementation. There is a detailed wikipedia page about x86 calling conventions which is motivating the wording of the standard.

For inspiration, look at functions such as vprintf(3). In practice their implementation in open source C standard libraries such as musl-libc should be interesting to you.

In theory (and in real life, in some cases on Linux with recent GCC, as a builtin) vprintf can be implemented in the compiler. But since you can take its address and pass it to some of your function, it also has to be a function in the C standard library.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547