Assert Macro in C

Level 5277 keystrokes

Defines a custom ASSERT macro that checks a condition and prints "Assert passed" or "Assert failed" with a message instead of stopping the program. With x = 10, the first two checks pass and the third, x == 5, fails.

C code

// Prints "Assert failed" if cond is false, otherwise "Assert passed", followed by msg
// (cond) is parenthesized for precedence; do-while(0) makes the macro act like one statement
1#define ASSERT(cond, msg) do { \
2 if (!(cond)) { \
3 printf("Assert failed: %s\n", msg); \
4 } else { \
5 printf("Assert passed: %s\n", msg); \
6 } \
7} while(0)
8
// The value being checked
9int x = 10;
// 10 > 0 is true: prints Assert passed: x must be positive
10ASSERT(x > 0, "x must be positive");
// 10 < 20 is true: prints Assert passed: x must be less than 20
11ASSERT(x < 20, "x must be less than 20");
// 10 == 5 is false: prints Assert failed: x must equal 5
12ASSERT(x == 5, "x must equal 5");

Output

Assert passed: x must be positive
Assert passed: x must be less than 20
Assert failed: x must equal 5
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.

  • "× 10
  • (× 9
  • )× 9
  • \× 8
  • ,× 6
  • ;× 6
  • {× 3
  • }× 3
  • =× 3
  • :× 2

More C examples at level 5

← C typing practice