Writing printf-like Functions
Variable arguments.
Functions that take a format string
The most powerful use of variadics is building printf-style functions that interpret a format string.
The format tells the function how many arguments follow and what type each one is.
#include <stdio.h>
#include <stdarg.h>
void myprint(const char *fmt, ...) {
printf("format was: %s\n", fmt);
}
int main(void) {
myprint("%d items\n", 5);
return 0;
}Walking the format string
Scan the format character by character. When you see a %, the next character is a conversion specifier telling you what type to read.
Everything else is printed literally.
#include <stdio.h>
#include <stdarg.h>
void scan(const char *fmt) {
for (const char *p = fmt; *p; p++) {
if (*p == '%') printf("[spec:%c]", *(p+1));
else putchar(*p);
}
putchar('\n');
}
int main(void) {
scan("x=%d y=%s");
return 0;
}All lessons in this course
- The stdarg Macros
- Writing printf-like Functions
- Type Safety Concerns
- Practical Examples