Programs & Examples
Variable Number of Arguments · Study material
A tiny printf driven by its format string
The format string tells the function what each argument is – the same mechanism the real printf uses.
#include <stdarg.h>
#include <stdio.h>
/* Supports %d, %s, %c and %% – the format string tells it what comes next */
static void say(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
for (const char *p = fmt; *p; p++) {
if (*p != '%' || p[1] == '\0') {
putchar(*p);
continue;
}
switch (*++p) {
case 'd': printf("%d", va_arg(ap, int)); break;
case 's': fputs(va_arg(ap, const char *), stdout); break;
case 'c': putchar(va_arg(ap, int)); break;
case '%': putchar('%'); break;
default: putchar('%'); putchar(*p);
}
}
va_end(ap);
}
int main(void) {
say("%s got grade %c with %d%% marks\n", "Ravi", 'A', 91);
return 0;
}
Ravi got grade A with 91% marks