Search code examples
cvariadic-functions

Implement Variadic function in C


I am trying to write wrapper for a log function with a printf-like behavior.

Can anyone tell me why the following example does not work?

#include <stdarg.h>

void message(int level, const char* format, ...)
{
    if(level > 3)
        return;

    static char msgBuff[1024] = {0};

    va_list argptr;
    va_start(argptr, format);
    snprintf(msgBuff, sizeof(msgBuff), format, argptr);
    va_end(argptr);
    printf("%s", msgBuff); // Dummy Call
}


int main()
{
    int a = 42;
    message(3, "This is a test: %s %i", "The answer is ", a);
    return 0;
}

Output:

This is a test:  0

Solution

  • The arguments to snprintf after the format string must be the individual arguments expected according to the conversion specifiers in the format string. argptr is not such an argument, so the call is incorrect.

    To print variable arguments using a va_list, call vsnprintf instead of snprintf.