0Pricing
C Academy · Lesson

Practical Examples

A logging function.

A logging function

A logger is the perfect real-world use of variadics. We want to call log_msg("user %s scored %d", name, score) just like printf.

This lesson builds a small, useful logging utility.

#include <stdio.h>
#include <stdarg.h>

void log_msg(const char *fmt, ...) {
    va_list a; va_start(a, fmt);
    vprintf(fmt, a);
    va_end(a);
    printf("\n");
}

int main(void) {
    log_msg("user %s scored %d", "Ann", 90);
    return 0;
}

Adding a severity level

Real loggers label messages with a level like INFO or ERROR. Add a fixed parameter before the format string for the level.

#include <stdio.h>
#include <stdarg.h>

void logf(const char *level, const char *fmt, ...) {
    printf("[%s] ", level);
    va_list a; va_start(a, fmt);
    vprintf(fmt, a);
    va_end(a);
    printf("\n");
}

int main(void) {
    logf("INFO", "started with %d workers", 4);
    return 0;
}

All lessons in this course

  1. The stdarg Macros
  2. Writing printf-like Functions
  3. Type Safety Concerns
  4. Practical Examples
← Back to C Academy