gpt4 book ai didi

调用 va_arg 的次数少于传递的参数数

转载 作者:太空宇宙 更新时间:2023-11-04 00:40:01 26 4
gpt4 key购买 nike

如果我调用 va_arg 的次数少于可变参数函数中传递的参数数量,是否会出现未定义的行为?

例如:

#include <stdarg.h>
void foo(unsigned n, ...) {
va_list ap;
int bar = 0;

va_start(ap, n);
if (n) bar = va_arg(ap,int);
// Do something with bar
}

int main() {
foo(2, 3, 4);
return 0;
}

该程序会导致未定义的行为吗?

最佳答案

您的程序确实导致未定义的行为,但不是因为您使用va_arg 的方式。那只是忽略了额外的参数,所以包含它似乎是在浪费打字。

导致未定义行为的原因是您没有在该函数中包含 va_end

来自规范(7.15.1.1 va_arg):

Each invocation of the va_arg macro modifies ap so that the values of successive arguments are returned in turn. ...If there is no actual next argument ... the behavior is undefined ...

来自 7.15.1.3 va_end:

...if the va_end macro is not invoked before the return, the behavior is undefined.

没有提到必须调用 va_arg 一定次数。正如您所见,va_end 很重要。

关于调用 va_arg 的次数少于传递的参数数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12890406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com