Conditional Macro in C

Level 5262 keystrokes

Defines DEBUG, a multi-line LOG macro that prints only when DEBUG is non-zero, and a VERSION string chosen with #ifdef at compile time. It prints [DEBUG] Starting program, Version: Debug 1.0 and [DEBUG] Program complete.

C code

// DEBUG is defined as 1, so debug output is switched on
1#define DEBUG 1
// A trailing backslash continues the macro on the next line; prints only if DEBUG is non-zero
// do { ... } while(0) makes LOG(...); behave like a single statement, even inside if/else
2#define LOG(msg) do { \
3 if (DEBUG) printf("[DEBUG] %s\n", msg); \
4} while(0)
5
// #ifdef only checks whether DEBUG is defined, not its value
6#ifdef DEBUG
// Chosen here, because DEBUG is defined
7 #define VERSION "Debug 1.0"
8#else
// Used only when DEBUG is not defined
9 #define VERSION "Release 1.0"
10#endif
11
// Prints [DEBUG] Starting program
12LOG("Starting program");
// Prints Version: Debug 1.0
13printf("Version: %s\n", VERSION);
// Prints [DEBUG] Program complete
14LOG("Program complete");

Output

[DEBUG] Starting program
Version: Debug 1.0
[DEBUG] Program complete
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
  • (× 7
  • )× 7
  • #× 7
  • ;× 4
  • \× 4
  • ,× 2
  • .× 2
  • %× 2
  • :× 1

More C examples at level 5

← C typing practice