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

The `inline` keyword purpose

The inline keyword purpose

What you'll learn: How to suggest that the compiler replace a function call with the actual function 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 pick up your phone, dial a friend, wait for them to answer, ask the question, get the answer, and hang up. The actual information exchange took two seconds, but the process of "calling" took thirty.

In C, every time you call a function, the CPU performs a similar overhead. It has to jump to a different part of the memory, save where it was, pass variables, and then jump back when finished. For a massive calculation, this doesn't matter. But for a tiny, one-line function used millions of times inside a loop, the "calling" takes longer than the "doing."

What inline does

The inline keyword is a suggestion to the compiler. You are telling it: "This function is so small and used so often that you shouldn't bother 'calling' it. Just copy-paste the function’s logic directly into the place where I used it."

When the compiler inlines a function, the "phone call" is eliminated. The code for the function becomes part of the flow of the surrounding code, making the program run slightly faster.

#include <stdio.h>

// We suggest inlining because this logic is tiny
inline int square(int x) {
    return x * x;
}

int main() {
    int val = 5;
    
    // Instead of jumping to a function, the compiler might 
    // effectively turn this into: int result = 5 * 5;
    int result = square(val);
    
    printf("Result: %d\n", result);
    return 0;
}

It’s a hint, not a command

It is important to remember that inline is just a request. Modern compilers are very smart; if they think inlining a function will actually make your program slower or too bloated, they will simply ignore your request. You should use inline for very short, simple functions (like math conversions or status checks) that are called frequently. If a function is fifty lines long, inlining it everywhere will make your final program file massive, which can actually slow things down!

Key takeaway

The inline keyword suggests that the compiler replace function calls with the actual code to eliminate the overhead of jumping between memory locations.