Macro with Parameters in C

Level 5217 keystrokes

Defines the function-like macros MAX, MIN and SQUARE, which the preprocessor replaces with their expressions before compilation. They print MAX: 20, MIN: 10 and SQUARE: 25.

C code

// Yields the larger of a and b with the ternary operator
// Each parameter is wrapped in parentheses so arguments like x + 1 keep the right precedence
1#define MAX(a, b) ((a) > (b) ? (a) : (b))
// Yields the smaller of a and b
2#define MIN(a, b) ((a) < (b) ? (a) : (b))
// Squares x; an argument such as i++ would be evaluated twice, a classic macro pitfall
3#define SQUARE(x) ((x) * (x))
4
// Expands to ((10) > (20) ? (10) : (20)), printing MAX: 20
5printf("MAX: %d\n", MAX(10, 20));
// Prints MIN: 10
6printf("MIN: %d\n", MIN(10, 20));
// Expands to ((5) * (5)), printing SQUARE: 25
7printf("SQUARE: %d\n", SQUARE(5));

Output

MAX: 20
MIN: 10
SQUARE: 25
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.

  • (× 22
  • )× 22
  • ,× 7
  • "× 6
  • :× 5
  • ;× 3
  • \× 3
  • #× 3
  • %× 3
  • ?× 2

More C examples at level 5

← C typing practice