如果附加参数的数量未知,我如何遍历 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;
}
最佳答案
在使用可变长度参数列表时,您必须以某种方式指明参数的数量(如果您正在编写可移植代码)。您现在可能会想“但是 printf 不需要您指定多个参数!”
是的,但是可以通过首先解析 % 格式说明符的格式字符串来推断该数字。
关于c - 如果参数数量未知,如何遍历 va_list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4800641/