C language variable parameter implementation example

  • 2020-04-02 02:20:01
  • OfStack

This code shows you how not to use it < Stdarg. H > Va_list, va_start, va_end macros to implement custom variable parameters and how to change the default %d, %f, %s format characters.


#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;
}


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/20140408102657.jpg? 20143810282 ">


Related articles: