How do I loop through a va_list if the number of additional arguments is unknown?
#include <stdio.h>
#include <stdarg.h>
int add(int x, int y, ...) {
va_list intargs;
int temp = 0;
va_start(intargs, y);
int i;
for (i = 0; i < 3; i++) { /* How can I loop through any number of args? */
temp += va_arg(intargs, int);
}
va_end(intargs);
return temp + x + y;
}
int main() {
printf("The total is %d.\n", add(1, 2, 3, 4, 5));
return 0;
}
You must indicate the number of parameters somehow (if you're writing portable code) when using variable length argument lists. You may be now thinking "But printf doesn't require you to indicate a number of arguments!"
True, however the number can be inferred by first parsing the format strings for % format specifiers.
Use a sentinel value as a terminator, e.g NULL
or -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With