我们可以两次调用 va_start() 而不在其间调用 va_end() 吗? [英] Can we call va_start() twice without calling va_end() in between?
问题描述
这是我的最小示例:
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
void print_strings_and_lengths(int count, ...)
{
va_list ap;
/* Print strings */
va_start(ap, count);
for (int i = 0; i < count; i++) {
char *s = va_arg(ap, char *);
printf("%d - %s\n", i, s);
}
/* Print string lengths */
va_start(ap, count); /* Is it okay to call va_start() again without calling va_end()? */
for (int i = 0; i < count; i++) {
char *s = va_arg(ap, char *);
printf("%d - %zu\n", i, strlen(s));
}
va_end(ap);
}
int main()
{
print_strings_and_lengths(3, "apple", "ball", "cat");
return 0;
}
这段代码对同一个变量参数列表调用了两次 va_start()
.va_end()
函数不会在两次调用之间调用.这段代码是定义明确的还是调用了未定义的行为?
This code is calling va_start()
twice on the same list of variable arguments. The va_end()
function is not called between the two calls. Is this code well defined or does it invoke undefined behavior?
推荐答案
C11 7.16.1/1:
C11 7.16.1/1:
[...] va_start
和 va_copy
宏的每次调用都应与 va_end
宏的相应调用相匹配.相同的功能.
[...] Each invocation of the
va_start
andva_copy
macros shall be matched by a corresponding invocation of theva_end
macro in the same function.
两个 va_start
调用都没有对应的 va_end
,因此代码会导致未定义的行为,无需诊断,因为上述引用不是约束的一部分.
There's no corresponding va_end
for both of the va_start
calls so the code causes undefined behaviour, with no diagnostic required as the above quote is not part of a Constraint.
这篇关于我们可以两次调用 va_start() 而不在其间调用 va_end() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!