• Home
  • 6.13 Inline Functions

6.13 Inline Functions

View Categories

6.13 Inline Functions

1 min read

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 inline specifier declares square() as an inline function.
  • square() accepts an int parameter and returns an int.
  • return number * number; calculates and returns the square of the supplied value.
  • square(5) calls the function with 5 as its argument.
  • The inline specifier 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 inline specifier is not present.
  • An inline function can be defined in multiple translation units when the definitions are identical.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *