Using terminator values to determine the end of va list
suggest changeA variadic function has to know where the argument list ends. One approach, used by the earlier sum example, is an explicit count. printf does not take a count; its format string describes the arguments. A count is easy to get wrong:
/* First argument specifies the number of parameters; the remainder are also int */
extern int sum(int n, ...);
/* But it's far from obvious from the code. */
sum(5, 2, 1, 4, 3, 6)
/* One argument was removed, but the count was not. */
sum(5, 2, 1, 3, 6) /* undefined behavior: va_arg reads past the arguments */
A terminator can replace the count. POSIX execlp uses a null pointer this way. The function below stops at NAN. Do not test x == NAN: a NaN compares unequal to every value, including itself. isnan is the test that works. Forgetting the terminator is undefined behavior, because va_arg then reads past the arguments. A real data value that is a NaN cannot be passed, because it would end the list.
#include <stdarg.h>
#include <stdio.h>
#include <math.h>
/* Sums args up until the terminator NAN */
double sum (double x, ...) {
double sum = 0;
va_list va;
va_start(va, x);
for (; !isnan(x); x = va_arg(va, double)) {
sum += x;
}
va_end(va);
return sum;
}
int main (void) {
printf("%g\n", sum(5., 2., 1., 4., 3., 6., NAN));
printf("%g\n", sum(1, 0.5, 0.25, 0.125, 0.0625, 0.03125, NAN));
}
Good terminator values:
- integer (supposed to be all positive or non-negative) —
0or-1 - floating point types —
NAN - pointer types —
NULL - enumerator types — some special value
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents