Search code examples
ccalling-convention

variadic args of unkown type


Using stdarg.h, I can only pull one type because I have to know the types im retrieving. How then, does printf manage to be a variadic function with any type, in C no less?


Solution

  • printf() uses the format string to determine at run time what sort of argument to pull.

    I haven't looked at the source to printf(), but one possible implementation might contain a switch something like this:

    switch (type_specifier)
    {
    case 's':
        str = va_arg(args, char *);
        /* output str as a string */
        break;
    case 'd':
        number = va_arg(args, int);
        /* output number as a decimal value */
        break;
    etc.
    etc.
    etc.
    }
    

    Note that a full implementation will be vastly more complex than this when you factor in all the various types of arguments, all the various sizes the arguments can be, the fact that "%*d" makes an extra va_arg() usage to get the width of the number, and that width specifiers can vary the output as well.