c语言可变参数实现示例
这段代码展示了如何不使用<stdarg.h>中的va_list、va_start、va_end宏来实现自定义可变参数以及如何改变默认的%d、%f、%s等格式字符。
#include <stdio.h>
#include <stdlib.h> // itoa() and ltoa()
#include <string.h> // strcat() and strlen()
// echo("$i, $s, $l, $c", arg1, arg2, arg3, arg4)
// $i -- int, $s -- string, $l -- long, $c -- char
void echo(char *fmt, ...)
{
int i, fmtlen = strlen(fmt);
int *args = (int *)((char *)(&fmt) +sizeof(char *));
char cbuff[BUFSIZ] = {'\0'}, nbuff[BUFSIZ] = {'\0'}; // #define BUFSIZ 512 in <stdio.h>
for (i = 0; i < fmtlen; i++)
{
if (('$' == fmt[i]) && ((i + 1) < fmtlen))
{
switch (fmt[i + 1])
{
case 's': strcat(cbuff, (char *)(*args));
break;
case 'c': cbuff[strlen(cbuff)] = (char)(*args);
break;
case 'i': itoa(*args, nbuff, 10); strcat(cbuff, nbuff);
break;
case 'l': ltoa((long)(*args), nbuff, 10); strcat(cbuff, nbuff);
break;
default: break;
}
++args, ++i;
}
else
cbuff[strlen(cbuff)] = fmt[i];
}
cbuff[strlen(cbuff) + 1] = '\0';
fputs(cbuff, stdout);
}
int main()
{
echo("arg_list = $i, $s, $l, $c", 2, "hello", 8, 'a'); // Si -- %d, $s -- %s, $l -- %ld, $c -- %c
return 0;
}