Course contentsShow
← C
Lesson 367 of 1,2195. FunctionsFree lesson

Compiler discretion with inlining

Compiler discretion with inlining

What you'll learn: Why the inline keyword is a suggestion to the compiler rather than a strict command, and how the compiler makes the final decision.

The "Polite Suggestion"

In C, when you prefix a function with the inline keyword, you are telling the compiler: "Instead of jumping to this function's location in memory, please just copy and paste the function's code directly into the spot where it's called."

Think of the inline keyword like a "High Priority" sticker on a package. You are signaling to the delivery driver (the compiler) that this package is important and should be handled quickly. However, the driver has the final say. If the package is too heavy or the delivery truck is already full, they might ignore the sticker and stick to the standard delivery route.

Why the compiler says "No"

You might think inlining everything would make your program lightning-fast, but that isn't true. If you inline a massive function that is called in fifty different places, your program's binary size will explode (code bloat). This can actually slow your program down because the CPU's instruction cache gets overwhelmed.

The compiler acts as a safety valve. It uses complex math to decide if inlining is worth it. It might ignore your inline request if:

  1. The function is too long or complex.
  2. The function is recursive (it calls itself).
  3. The function uses varargs (variable arguments).
  4. The compiler calculates that the overhead of a jump is actually smaller than the cost of bloated code.

Code Example: A Suggestion

#include <stdio.h>

// We suggest inlining this because it is tiny and called frequently
inline int square(int x) {
    return x * x;
}

int main() {
    int val = 5;
    // The compiler will likely replace this call with (5 * 5)
    int result = square(val);
    
    printf("Result: %d\n", result);
    return 0;
}

Conversely, if the compiler sees a function it thinks should be inlined—even if you didn't use the keyword—it might decide to inline it anyway! In modern C, the compiler is often smarter than the programmer when it comes to these micro-optimizations.

Key takeaway

The inline keyword is a hint, not a command; the compiler will ultimately decide whether to inline code based on its own efficiency calculations.