what’s the difference between the printf and vprintf function families, and when should I use one over the other?

printf() and friends are for normal use. vprintf() and friends are for when you want to write your own printf()-like function. Say you want to write a function to print errors:

int error(char *fmt, ...)
{
    int result;
    va_list args;
    va_start(args, fmt);
    // what here?
    va_end(args);
    return result;
}

You’ll notice that you can’t pass args to printf(), since printf() takes many arguments, rather than one va_list argument. The vprintf() functions, however, do take a va_list argument instead of a variable number of arguments, so here is the completed version:

int error(char *fmt, ...)
{
    int result;
    va_list args;
    va_start(args, fmt);
    fputs("Error: ", stderr);
    result = vfprintf(stderr, fmt, args);
    va_end(args);
    return result;
}

Leave a Comment