c++ - "va_start"的第二个参数

标签 c++ c variadic-functions

对于下面的代码:

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/

相关文章:

c++ - 符号可见性是否保护共享库免受滥用/破解?

c - 可能的 4 位数字,其各个数字之和等于 n

克隆系统调用 OS X 未链接 - undefined symbol

c - For循环不将数组内的特殊字符识别为单个字符

c++ - 如何从 std::vector 转换为 args

c++ - 如何转换转发的参数包?

Android NDK JNI 未定义对 C++ 源方法的引用

c++ - 创建 .svg 条形图

c++ - 针对简单 if..else 语句的递归 Variadic 函数调用的性能

c++ - 为什么 C++ 语法如此复杂?