← The C Language
Lesson 32 of 77 · 10 XP
Inline functions: inline
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A function call has a small overhead: pass the arguments, jump, come back. For tiny functions called millions of times, this can be noticeable.
The word inline is a hint to the compiler: "you may insert the function's body right at the place of the call".
static inline int max(int a, int b)
{
return a > b ? a : b;
}
What's important to understand:
- it's a hint, not an order: a modern compiler with
-O2decides by itself what to inline, and often does so without anyinline; - in C,
inlinehas tricky linking rules. The simplest and most reliable option isstatic inline: the function is visible only in its own file; inlinefunctions are often put into header files instead of macros. Unlike a macro, a function has type checking, and its argument is evaluated exactly once.
#define MAX(a, b) ((a) > (b) ? (a) : (b))
MAX(i++, j) // i++ may run TWICE — an inline function doesn't have this problem
Task. Write static inline int clamp(int x, int lo, int hi), which "clamps" a number into the range [lo, hi]. The program reads x lo hi and prints the result.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.