我有以下函数将传递的参数写入二进制文件。
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
的整数值(例如 char
、bool
或 short
)对于采用可变数量参数的函数,它将被转换为 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/