不定参数调用实现:
三个宏的使用va_arg()、va_start()和va_end()
上述的宏原型如下所示:
C代码 收藏代码
type va_arg(va_list argptr, type);
void va_end(va_list argptr);
void va_start(va_list argptr, last_parm);
它们都包含在头文件stdarg.h中.
void fun(char *fmt,...){
va_list ap;
int d;
double df;
char *tmp=NULL,*va=NULL,c;
char *last=NULL,*word=NULL,*msg=NULL;
char varword[512];
char res[512];
va_start(ap,fmt);
word=last=va=fmt;
va++;/*because the d/c/s/f cant be the first and may cause bug*/
while (*va) {
switch (*va) {
case 'd':
tmp = va;
while (*--tmp != '%' && tmp != last)
;
if (tmp == last){
/*in case the % is the first character */
if(last != fmt || *fmt!='%')
break;
}
strncpy(varword + strlen(varword), word, va - word + 1);
d = va_arg(ap,int);
sprintf(res, varword, d);
strcpy(varword, res);
last = tmp;
word = va + 1;
break;
case 'c':
tmp = va;
while (*--tmp != '%' && tmp != last)
;
if (tmp == last){
if(last != fmt || *fmt!='%')
break;
}
strncpy(varword + strlen(varword), word, va - word + 1);
c = va_arg(ap,char);
sprintf(res, varword, c);
strcpy(varword, res);
last = tmp;
word = va + 1;
break;
case 's':
tmp = va;
while (*--tmp != '%' && tmp != last)
;
if (tmp == last){
if(last != fmt || *fmt!='%')
break;
}
strncpy(varword + strlen(varword), word, va - word + 1);
msg = va_arg(ap,char*);
sprintf(res, varword, msg);
strcpy(varword, res);
last = tmp;
word = va + 1;
break;
case 'f':
tmp = va;
while (*--tmp != '%' && tmp != last)
;
if (tmp == last){
if(last != fmt || *fmt!='%')
break;
}
strncpy(varword + strlen(varword), word, va - word + 1);
df = va_arg(ap,double);
sprintf(res, varword, df);
strcpy(varword, res);
last = tmp;
word = va + 1;
break;
}
va++;
}
va_end(ap);
if(word!=va) strcat(res,word);
printf("the result is :%s\n",res);
}