0 day streak
c / intermediate
Snippet

Stringification and Concatenation in Macros

The '#' operator converts a macro argument into a string literal (stringification). The '##' operator joins two tokens together during preprocessing (concatenation), allowing for dynamic generation of variable names or code blocks.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define DEBUG_PRINT(var) printf(#var " = %d\n", var)
#define MAKE_NAME(prefix, suffix) prefix ## _ ## suffix
int main() {
int my_val = 42;
DEBUG_PRINT(my_val);
int MAKE_NAME(user, id) = 101;
printf("user_id = %d\n", user_id);
return 0;
}
Breakdown
1
#var
Converts the name of the variable passed to the macro into a string literal.
2
prefix ## _ ## suffix
Glues tokens together; for example, 'user' and 'id' become the single identifier 'user_id'.