Inline Function in C Tutorial

In this section, we will learn what the inline function is and how to use it in C.

What is inline function in C?

The final result of calling a compiler on a source code is an executable program. This program consists of a set of machine language instructions and when we want to run the program, the operating system will load the content to the memory and so each instruction of the program will be stored in a separate place there.

At run time, when the program is running, the computer goes through each of these instructions one by one to execute them.

But when we call a function like `functionB` within the body of another function like `functionA` in a program, the computer needs to jump from the current memory location and go to the memory address where the instructions of the `functionB` is stored. After the execution of the `functionB` is finished, again the computer needs to jump back from `functionB` to the memory location where the call to the `functionB` happened.

Moving back and forth and keeping track of where to jump can result of wasting the CPU’s time.

This is where `inline function` can be helpful.

Basically, when we turn a function into an inline function, the compiler will check the source code and will replace any call to an inline-function with its actual body. This way when the computer is running the program, there’s no need to jump to another memory location in order to run a function.

C Inline Function Syntax:

To turn a normal function into an inline-function, we must at least do one of these two actions:

  • Preface the function declaration with the keyword `inline` (start the function declaration with the keyword inline).
  • Preface the function definition with the keyword `inline` (start the function definition with the keyword inline).

Example: creating and using inline function in C

#include <stdio.h>

inline void printName();
int main() {

    printName();
    printName();
    printName();
    return 0;
}
void printName(){
    printf("My name is John Doe\n");
}

In this example, we’ve turned the `printName()` function into an inline function. So at compile time, the compiler will check any call to the `printName()` function and will replace that call with the body of the function itself.

So at compile time, the source-code above will be turned into this:

#include <stdio.h>

inline void printName();
int main() {

    printf("My name is John Doe\n");
    printf("My name is John Doe\n");
    printf("My name is John Doe\n");
    return 0;
}
void printName(){
    printf("My name is John Doe\n");
}

Then at runtime we will get this output:

My name is John Doe

My name is John Doe

My name is John Doe

Inline Function in C Note:

The compiler might not honor our request to make a function inline. This is because the function might be too large or it calls itself (recursion is not allowed for inline functions).

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies