Function with inline keyword

Example

An inline function can be written in C or C++ like this:

inline void swap(int *m, int *n)
{
    int tmp = *m;
    *m = *n;
    *n = tmp;
}

Then, a statement such as the following:

swap(&x, &y);

may be translated into (if the compiler decides to do the inlining, which typically requires optimization to be enabled):

int tmp = x;
x = y;
y = tmp;

When implementing a sorting algorithm doing lots of swaps, this can increase the execution speed.

In C, an inline function is a type of function where the compiler replaces the function call with its actual code of the function, invoked through the usual function call mechanism. This can improve performance by reducing the overhead of function calls. The inline keyword is used to declare such functions, which are normally small and frequently called.

Syntax

inline return_type function_name(parameters) {
   // Function body
}

Static Inline Function

We can use the static keyword before the inline function. This forces the compiler to treat the function with internal linkage and ensures that it is considered during the linking process, allowing the program to compile and run successfully. Though the inlining still depends on the compiler’s optimization level.

#include <stdio.h>

// Inline function in C
static inline int foo() {
    return 2;
}

int main() {
    int res;

    // inline function call
    res = foo();
    printf("%d", res);
    return 0;
}