Inline Function in C

Level 5339 keystrokes

Defines max, min and clamp as static inline functions, a hint that the compiler may replace each call with the function body, and builds clamp from the other two. It prints max(5, 3): 5, min(5, 3): 3 and clamp(10, 0, 5): 5.

C code

// static gives internal linkage; inline suggests replacing calls with the body
// inline is only a hint: the compiler decides whether to inline
1static inline int max(int a, int b) {
// Returns the larger value using the ternary operator
2 return (a > b) ? a : b;
3}
4
// The same pattern for the minimum
5static inline int min(int a, int b) {
// Returns the smaller value
6 return (a < b) ? a : b;
7}
8
// An inline function may call other inline functions
9static inline int clamp(int val, int lo, int hi) {
// Raises val to at least lo, then caps it at hi
10 return min(max(val, lo), hi);
11}
12
// Prints max(5, 3): 5
13printf("max(5, 3): %d\n", max(5, 3));
// Prints min(5, 3): 3
14printf("min(5, 3): %d\n", min(5, 3));
// max(10, 0) is 10 and min(10, 5) is 5, so 10 is clamped to 5
15printf("clamp(10, 0, 5): %d\n", clamp(10, 0, 5));

Output

max(5, 3): 5
min(5, 3): 3
clamp(10, 0, 5): 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.

  • ,× 17
  • (× 16
  • )× 16
  • ;× 6
  • "× 6
  • :× 5
  • {× 3
  • }× 3
  • \× 3
  • %× 3

More C examples at level 5

← C typing practice