对于下面的代码:
void fun(char *msg, int n, int m, ...) {
va_list ptr;
va_start(ptr, m); // Question regarding this line
printf("%d ", va_arg(ptr, int));
}
函数调用如下:
fun("Hello", 3, 54, 1, 7);
我的问题是关于上面评论的行。我尝试了该行的以下三个版本:
va_start(ptr, msg);
va_start(ptr, n);
va_start(ptr, m);
在所有这三种情况下,我都得到“1”作为输出。 From what I have read , va_start
的第二个参数应该是函数 fun()
的参数列表中的最后一个参数,即 va_start(ptr, m);
应该是正确的调用。那么为什么我在所有三种情况下都得到相同的输出。
[我在 Ideone 上运行了该程序,如果这有什么影响的话。]
最佳答案
根据 C 标准,您显示的前两个调用是未定义的行为;只有传递最后命名参数的调用才是正确的。但是,您在 gcc 上的表现良好,因为 gcc 编译器忽略 va_start
的第二个参数,使用不同的技术来查找参数列表的末尾:
The traditional implementation takes just one argument, which is the variable in which to store the argument pointer. The ISO implementation of
va_start
takes an additional second argument. The user is supposed to write the last named argument of the function here. However,va_start
should not use this argument. The way to find the end of the named arguments is with the built-in functions described below {link}.
关于c++ - "va_start"的第二个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24824965/