gpt4 book ai didi

va_arg 中的字符类型

转载 作者:太空狗 更新时间:2023-10-29 14:52:23 25 4
gpt4 key购买 nike

我有以下函数将传递的参数写入二进制文件。

void writeFile(FILE *fp, const int numOfChars, ...)
{
va_list ap;
va_start(ap, numOfChars);
for(int i = 0; i < numOfChars; i++)
{
const char c = va_arg(ap, char);
putc(c, fp);
}
va_end(ap);
}

编译时,我从编译器收到以下警告

 warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg
has undefined behavior because arguments will be promoted to 'int' [- Wvarargs]

现在据我了解,C 想要将 char 类型提升为 int。为什么C要这样做?其次,将 int 转换回 char 的最佳解决方案是什么?

最佳答案

Now as I understand it, C wants to promote char type to int. Why does C want to do this?

因为标准就是这么说的。如果您传递的转换等级小于 int 的整数值(例如 charboolshort)对于采用可变数量参数的函数,它将被转换为 int。据推测,其原因在于性能,过去(事实上,现在通常仍然如此)更好地传递与机器字边界对齐的值。

Second, is the best solution to cast the int back to a char?

是的,但你甚至不需要强制转换,隐式转换就可以:

char ch = va_arg(ap, int);

关于va_arg 中的字符类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054194/

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