C語言可變參數(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編譯通過
#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指向空指針.
具體的實現(xiàn),在不同的編譯環(huán)境下有所不同.
擴展閱讀:單片機C語言編程心得