Table of Contents
An inline function is a function declared with the inline specifier. The specifier allows the function to be defined in multiple translation units without violating the One Definition Rule, provided the definitions are identical. It also indicates that the function is suitable for inline substitution, although the compiler is not required to perform such substitution.
Inline functions are commonly used for small function definitions, particularly when the function is defined in a header file.
Source Code #
#include <iostream>
inline int square(int number)
{
return number * number;
}
int main()
{
int result = square(5);
std::cout << "Square: " << result << '\n';
return 0;
}
Output #
Square: 25
Explanation #
- The
inlinespecifier declaressquare()as an inline function. square()accepts anintparameter and returns anint.return number * number;calculates and returns the square of the supplied value.square(5)calls the function with5as its argument.- The
inlinespecifier does not require the compiler to replace the function call with the function body. - Modern compilers can perform function inlining as an optimization even when the
inlinespecifier is not present. - An inline function can be defined in multiple translation units when the definitions are identical.
return 0;terminates the program successfully.