如果附加参数的数量未知,我如何遍历va_list?
#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;
}
Run Code Online (Sandbox Code Playgroud)
Jas*_*run 18
在使用可变长度参数列表时,必须以某种方式指示参数的数量(如果您正在编写可移植代码).您现在可能正在考虑"但是printf并不要求您指出一些论点!"
是的,但是可以通过首先解析%格式说明符的格式字符串来推断出数字.