typestar

Variadic macros in C

__VA_ARGS__ forwards any number of arguments, which is how logging macros work.

#include <stdio.h>

#define LOG(fmt, ...) \
    fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)

#define TRACE() LOG("reached %s", __func__)

void noisy(int value) {
    LOG("starting");
    LOG("value is %d", value);
    TRACE();
}

How it works

  1. ... in the parameter list captures the rest.
  2. __VA_ARGS__ expands to them, commas included.
  3. The leading ## swallows the comma when nothing was passed.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
240
Tokens
36
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 22 seconds.

Type this snippet

Step 2 of 3 in Text manipulation, step 6 of 12 in Preprocessor & headers.

← Previous Next →