“va_start"的第二个参数 [英] Second argument of "va_start"
问题描述
对于以下代码:
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);
我的问题是关于上面评论的那一行.我尝试了该行的以下三个版本:
My question is regarding the line commented above. I tried the following three versions of that line:
va_start(ptr, msg);
va_start(ptr, n);
va_start(ptr, m);
在所有三种情况下,我的输出都是1".从我读到的内容,va_start
的第二个参数应该是函数fun()
的参数列表中的最后一个参数,即va_start(ptr, m);
应该是正确的调用.那么为什么我在所有三种情况下都得到相同的输出.
In all the three cases I am getting "1" as the output. From what I have read, the second argument of va_start
should be the last argument in the parameter list of the function fun()
, i.e., va_start(ptr, m);
should be the correct call. So why am I getting the same output in all the three cases.
[我在 Ideone 上运行程序,如果这有任何后果.]
推荐答案
根据 C 标准,您显示的前两个调用是未定义的行为;只有传递最后一个命名参数的调用才是正确的.但是,您在 gcc 上获得了良好的行为,因为 gcc 编译器会忽略 va_start
的第二个参数,使用不同的技术来查找参数列表的末尾:
The first two calls that you show are undefined behavior according to the C standard; only the call that passes the last named parameter is correct. However, you get good behavior on gcc, because gcc compilers ignore the second parameter of va_start
, using a different technique to find the end of the argument list:
传统的实现只需要一个参数,即存储参数指针的变量.va_start
的 ISO 实现需要额外的第二个参数.用户应该在此处写入函数的最后一个命名参数.但是,va_start
不应使用此参数.找到命名参数末尾的方法是使用下面描述的内置函数 {link}.
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}.
这篇关于“va_start"的第二个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!