R
Richard Heathfield
I was recently asked whether it is legal to start processing a variable
argument list a second time, /before/ you've finished with it the first
time. (I have no idea why the questioner might want to do this, I'm afraid.
Since he's normally fairly bright, I presume he had a good reason for
asking.)
The following code illustrates the point, I think (but don't use it as a
va_arg tutorial!, as it kinda assumes there are at least six args after the
named arg):
#include <stdio.h>
#include <stdarg.h>
int foo(int i, ...)
{
va_list ap = {0};
va_list aq = {0};
int sum = i;
va_start(ap, i);
sum += va_arg(ap, int);
sum += va_arg(ap, int);
va_start(aq, i);
sum += va_arg(ap, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
sum += va_arg(aq, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
va_end(ap);
sum += va_arg(aq, int);
sum += va_arg(aq, int);
va_end(aq);
return sum;
}
int main(void)
{
printf("%d\n", foo(6, 5, 4, 3, 2, 1, 0));
return 0;
}
Having read through the relevant section of C99, I could find no
standard-based reason why this interleaving should not work (and, indeed,
it does work on the single compiler I tested the code with).
Did I miss something, or am I right in thinking this is a legal,
well-defined technique?
argument list a second time, /before/ you've finished with it the first
time. (I have no idea why the questioner might want to do this, I'm afraid.
Since he's normally fairly bright, I presume he had a good reason for
asking.)
The following code illustrates the point, I think (but don't use it as a
va_arg tutorial!, as it kinda assumes there are at least six args after the
named arg):
#include <stdio.h>
#include <stdarg.h>
int foo(int i, ...)
{
va_list ap = {0};
va_list aq = {0};
int sum = i;
va_start(ap, i);
sum += va_arg(ap, int);
sum += va_arg(ap, int);
va_start(aq, i);
sum += va_arg(ap, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
sum += va_arg(aq, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
sum += va_arg(ap, int);
sum += va_arg(aq, int);
va_end(ap);
sum += va_arg(aq, int);
sum += va_arg(aq, int);
va_end(aq);
return sum;
}
int main(void)
{
printf("%d\n", foo(6, 5, 4, 3, 2, 1, 0));
return 0;
}
Having read through the relevant section of C99, I could find no
standard-based reason why this interleaving should not work (and, indeed,
it does work on the single compiler I tested the code with).
Did I miss something, or am I right in thinking this is a legal,
well-defined technique?