A function specifier defines a certain property or behavior of a function in C. The inline
function specifier suggests that the compiler replace each call of that function with a separate code present inside it.
It is important to note that using the
inline
specifier does not necessarily mean that the function will be inlined. It just acts as a suggestion for the compiler, and the compiler decides if the function will be inlined.
inline
specifierWhen we call a simple function in C, the following steps take place:
When a function is inlined, executing the above steps is not incurred, which increases the program’s efficiency.
To gain the above-stated efficiency, the compiler sometimes performs automatic inlining. It can make a function inline even if we do not use the inline
specifier.
Following are some of the cases when a function is automatically inlined:
static
keywordIn C, when we write the inline
specifier, we are actually suggesting that we’re writing an implementation of the function that will be executed only if the compiler decides to inline it.
This means that compiler looks for another definition of the function if it is not inlined.
To overcome this issue, we use static
keyword. It tells the compiler that it should use the implementation we provided and not look for another one.
In this example, we will print a simple “Hello, World!” statement using an inline function.
In the following snippet of code, the function call (line 9) will be replaced by the body of the function (line 4) if the compiler inlines the function:
#include<stdio.h>static inline void printHelloWorld() {printf("Hello, World! \n");}void main() {// calling the inline functionprintHelloWorld();}
In this example, we will print a statement and then return the integer 10 from an inline function.
In the following piece of code, the function call in line 10 will be replaced by the function body (line 4-5):
#include<stdio.h>static inline int returnAnInteger() {printf("Returning an integer \n");return 10;}void main() {// calling the inline functionint x = returnAnInteger();printf(" %d ", x);}
Free Resources