Variadic macros

Preprocessor

//... takes any number of arguments, __VA_ARGS__ pastes them
//with their commas
#define LOG(...) printf("[log] " __VA_ARGS__)

LOG("started\n");
//printed "[log] started"
LOG("x is %d, y is %d\n", 3, 4);
//printed "[log] x is 3, y is 4"

//C23: __VA_OPT__(,) puts the comma only when there are arguments,
//otherwise DEBUG("no arguments") would end in printf("...",)
#define DEBUG(format, ...) printf("[debug] " format "\n" __VA_OPT__(,) __VA_ARGS__)
DEBUG("no arguments");
//printed "[debug] no arguments"
DEBUG("%d + %d = %d", 2, 3, 2 + 3);
//printed "[debug] 2 + 3 = 5"

//the arguments become an array: a compound literal,
//and sizeof counts them
int sumOf(const int numbers[], size_t count) {
    int sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += numbers[i];
    }
    return sum;
}
#define SUM(...) sumOf((int[]){__VA_ARGS__}, \
    sizeof((int[]){__VA_ARGS__}) / sizeof(int))

int total = SUM(1, 2, 3, 4);
//total is 10

//# makes a string of all the arguments
#define TEXT(...) #__VA_ARGS__
const char *list = TEXT(red, green, blue);
//list is "red, green, blue"

printf("total is %d\n", total);
printf("list is %s\n", list);