Interview Questions

How can I write a function that takes a format string and a variable number of arguments

C Interview Questions and Answers


(Continued from previous question...)

How can I write a function that takes a format string and a variable number of arguments

Q: How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work?

A: Use vprintf, vfprintf, or vsprintf. These routines are like their counterparts printf, fprintf, and sprintf, except that instead of a variable-length argument list, they accept a single va_list pointer.
As an example, here is an error function which prints an error message, preceded by the string ``error: '' and terminated with a newline:
#include <stdio.h>
#include <stdarg.h>

void error(const char *fmt, ...)
{
va_list argp;
fprintf(stderr, "error: ");
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
va_end(argp);
fprintf(stderr, "\n"); }

(Continued on next question...)

Other Interview Questions