This code shows how to implement custom variable parameters without using the va_list, Va_start, va_end macros in <stdarg.h>, and how to change the default format characters for%d,%f, and%s.
Copy Code code as follows:
#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] = {' I '}, Nbuff[bufsiz] = {' n '}; #define BUFSIZ <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] = ';
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;
}