c中va_arg函数中的变量参数类型
我收到gcc编译器的警告,如果执行以下代码,程序将中止。我不知道为什么?如果有人澄清的话,会很有帮助的c中va_arg函数中的变量参数类型,c,C,我收到gcc编译器的警告,如果执行以下代码,程序将中止。我不知道为什么?如果有人澄清的话,会很有帮助的 #include<stdio.h> #include<stdarg.h> int f(char c,...); int main() { char c=97,d=98; f(c,d); return 0; } int f(char c,...) { va_list li; va_start(li,c); char d=va_arg(
#include<stdio.h>
#include<stdarg.h>
int f(char c,...);
int main()
{
char c=97,d=98;
f(c,d);
return 0;
}
int f(char c,...)
{
va_list li;
va_start(li,c);
char d=va_arg(li,char);
printf("%c\n",d);
va_end(li);
}
变量函数的参数进行默认参数升级;小于
int
(例如char
)的任何内容首先转换为int
(而float
转换为double
)
所以
va_arg(li,char)
永远都不正确;使用va_arg(li,int)
。是的,这似乎是C标准中的一个怪癖。但是,这似乎只与va_arg()
有关
您可以查看
printf()
的各种实现,了解如何克服这一问题。例如,很容易阅读。为什么在k&r书中没有提到它?有趣的是,有些编译器有一个va_arg()
,如果使用char
,它将四舍五入为int
。Microsoft Visual Studio 2005将以下内容作为其va_arg()
:\define\u crt\u va_arg(ap,t)(*(t*)((ap+=\u INTSIZEOF(t))-\u INTSIZEOF(t))
以及\define\u INTSIZEOF(n)((sizeof(n)+sizeof(int)-1)和(sizeof(int)-1))的附加宏定义。
warning: 'char’ is promoted to ‘int’ when passed through ‘...’ [enabled by default]
note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
note: if this code is reached, the program will abort