Course contentsShow
← C
Lesson 1194 of 1,21916. Practice and ProjectsFree lesson

Using `inline` functions effectively

Using inline functions effectively

What you'll learn: How to use the inline keyword to suggest that the compiler replace a function call with the function's actual code to save time.

The Cost of a Phone Call

Imagine you are cooking and need to know how many teaspoons are in a tablespoon. You stop what you’re doing, pick up the phone, dial a friend, ask the question, listen to the answer, and then hang up to resume cooking. The actual answer takes one second to hear, but the process of calling takes thirty seconds.

In C, every time you call a function, the CPU does a little bit of "administrative work." It saves where it was, jumps to a new memory location, passes arguments, and then jumps back. For large functions, this overhead is unnoticeable. But for a tiny function that just adds two numbers, the "phone call" can take longer than the math itself.

Bringing the Code to the Caller

The inline keyword is your way of telling the compiler: "This function is so small and used so often that you should just copy-paste the logic directly into the spot where I called it." This eliminates the overhead of the jump.

#include <stdio.h>

// We suggest the compiler "inline" this tiny calculation
static inline int square(int x) {
    return x * x;
}

int main() {
    int sum = 0;
    
    // Instead of jumping to 'square' 1000 times, 
    // the compiler can just put 'i * i' right here.
    for (int i = 0; i < 1000; i++) {
        sum += square(i);
    }
    
    printf("Total: %d\n", sum);
    return 0;
}

When to Use It

Optimization is a balancing act. If you inline a massive function that is called in fifty different places, your final program file (the binary) will become bloated and huge because that code is repeated fifty times.

Use inline only for tiny, frequently called functions (like simple math or getters). Also, remember that inline is just a hint. Modern compilers are very smart; they might ignore your suggestion if they think it will hurt performance, or they might inline a function you didn't even mark!

Key takeaway

Use inline for small, high-frequency functions to remove call overhead, but avoid it for large functions to prevent code bloat.