what is inline function

10 months ago 29
Nature

An inline function in C and C++ is a function qualified with the keyword "inline." This serves two main purposes. First, it suggests to the compiler that it should substitute the body of the function inline by performing inline expansion, which means inserting the function code at the address of each function call, thereby saving the overhead of a function call. Second, it changes the linkage behavior, which is necessary due to the separate compilation and linkage model of C/C++. The definition of the function must be duplicated in all translation units where it is used to allow inlining during compiling, which can cause a collision during linking if the function has external linkage.

An inline function is expanded in line when it is called, and the whole code of the inline function gets inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler at compile time. An inline function may increase efficiency if it is small, but it may increase compile time overhead if the code inside the inline function is changed, as all the calling locations have to be recompiled.

Some effects of inlining include an increase in program size in most cases, potential improvement in execution time by avoiding call overhead, and an increase in practical coupling, which can lead to recompilation of the caller when the inlined callee changes.

In Kotlin, when an inline function is public or protected but is not a part of a private or internal declaration, it is considered a modules public API.

The inline keyword in C++ tells the compiler to substitute the code within the function definition for every instance of a function call. It is best used for small functions such as accessing private data members, as it saves the overhead on function calls and benefits less from inlining for longer functions.