Stringification Macro in C

Level 5290 keystrokes

Uses the # operator to turn macro arguments into string literals: PRINT_VAR prints an expression's source text next to its value, and LOCATION builds "file:line" with a two-level macro so __LINE__ expands first. It prints count = 42, total = 100, count + total = 142 and the location, such as main.c:12.

C code

// # turns the argument into a string literal: STRINGIFY(hello) becomes "hello"
1#define STRINGIFY(x) #x
// The extra level expands x first, so TOSTRING(__LINE__) gives "12" instead of "__LINE__"
2#define TOSTRING(x) STRINGIFY(x)
// Adjacent string literals are joined into one: "main.c" ":" "12" becomes "main.c:12"
3#define LOCATION __FILE__ ":" TOSTRING(__LINE__)
// #var is the argument's source text, joined with " = %d\n" into the format string
4#define PRINT_VAR(var) printf(#var " = %d\n", var)
5
// Two variables to display
6int count = 42;
7int total = 100;
8
// Prints count = 42
9PRINT_VAR(count);
// Prints total = 100
10PRINT_VAR(total);
// A whole expression also works: prints count + total = 142
11PRINT_VAR(count + total);
12
// Prints the file name and line, e.g. Location: main.c:12 (it depends on the source file)
13printf("Location: %s\n", LOCATION);

Output

count = 42
total = 100
count + total = 142
Location: main.c:12
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • _× 12
  • (× 10
  • )× 10
  • ;× 6
  • "× 6
  • #× 6
  • =× 3
  • ,× 2
  • :× 2
  • \× 2

More C examples at level 5

← C typing practice