C語(yǔ)言可變參數(shù)函數(shù)使用總結(jié)
//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);
}
//調(diào)用
TestFun((char*)"this is %d,%c,%x",1234,'6',0x12345);
//WIN-TC編譯通過(guò)
#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指向第一個(gè)變參.
var_arg(ap,type),//返回變參的實(shí)際值.
var_end(ap).//是ap指向空指針.
具體的實(shí)現(xiàn),在不同的編譯環(huán)境下有所不同.
擴(kuò)展閱讀:?jiǎn)纹瑱C(jī)C語(yǔ)言編程心得
編輯:admin 最后修改時(shí)間:2018-05-19