C语言可变参数函数使用总结
2013-05-13 来源:21IC
//ADS1.2下编译使用
void TestFun(char* fmt,...)
{
int ch;
char selch = 0;
va_list ap = NULL;
va_start(ap, fmt);
do
{
selch = *fmt;
if (selch!=\'%\')
{
putchar(*fmt);
}
else
{
selch = *++fmt;
switch(selch)
{
case \'c\':
ch = va_arg(ap, int);
printf("%c",ch);
break;
case \'d\':
ch = va_arg(ap,int);
printf("%d",ch);
break;
case \'x\':
ch = va_arg(ap, int);
printf("%#x",ch);
break;
}
}
++fmt;
}while(*fmt!=\'\');
va_end(ap);
}
//调用
TestFun((char*)"this is %d,%c,%x",1234,\'6\',0x12345);
//WIN-TC编译通过
#i nclude
/************************************************************
typedef void *va_list;
#define va_start(ap, parmN) (ap = ...)
#define va_arg(ap, type) (*((type *)(ap))++)
#define va_end(ap)
***************************************************/
void TestFun(cosnt char* fmt,...)
{
int ch;
long i32value = 0;
char selch = 0;
va_list ap = 0;
va_start(ap, fmt);
do
{
selch = *fmt;
if (selch!=\'%\')
{
putch(*fmt);
}
else
{
selch = *++fmt;
switch(selch)
{
case \'c\':
ch = va_arg(ap, int);
printf("%c",ch);
break;
case \'d\':
ch = va_arg(ap,int);
printf("%d",ch);
break;
case \'x\':
ch = va_arg(ap, int);
printf("%#x",ch);
break;
case \'l\':
if(*++fmt== \'d\')
{
i32value = va_arg(ap, long);
printf("%ld",i32value);
}
else
{
putch(\'l\');
if(*fmt!=0)
{
putch(*fmt);
}
}
break;
default:
break;
}
}
++fmt;
}while(*fmt!=\'\');
va_end(ap);
}
void main(void)
{
TestFun("this is %d,%c,%x,%ld",1234,\'6\',0x2345,(long)12345678);
getch();
}
void main(void)
{
TestFun("this is %d,%c,%x,%ld",1234,(char)\'6\',0x2345,(long)12345678);
getch();
}
上述的example使用宏定义, var_start(ap, pareN),var_arg(ap,type),var_end(ap).
var_start(ap, pareN) //是ap指向第一个变参.
var_arg(ap,type),//返回变参的实际值.
var_end(ap).//是ap指向空指针.
具体的实现,在不同的编译环境下有所不同.