CodeBlanks Logo Icon CodeBlanks

inline

Learn the inline keyword and linker impact.

Inline

The inline keyword allows a function to be defined in multiple translation units; it relaxes the ODR (One Definition Rule). The compiler may replace a function call with the body, but this decision belongs to the compiler.

In modern C++ inline is not really a speed hint but an ODR relaxant. The compiler already makes the best decision at -O2 and above. __attribute__((always_inline)) (GCC/Clang) forces inline; but misuse bloats code and hurts cache friendliness.

ODR relaxation

Normally a function can have only one definition (ODR). But inline functions may be defined in multiple translation units; the linker merges them. This lets you put function definitions in a header file.

Example: in a utils.hpp header you write inline int square(int x) { return x * x; }. Two .cpp files include this header; both see the definition and no link error occurs. Without inline this would be an ODR violation.

Practice Write the inline square function

Write inline int square(int x) with body return x * x;. In main write std::cout << square(6);.

Starter code

main.cpp
#include <iostream>

// Define the inline square function here

int main() {
    // Call square and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

inline int square(int x) {
    return x * x;
}

int main() {
    std::cout << square(6);
    return 0;
}

Expected output

36

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the inline keyword do in modern C++?

main.cpp
inline int square(int x) { return x * x; }
  • Only speeds things up
  • Deletes the code
  • Removes classes
  • Relaxes ODR, compiler decides on inlining Correct answer

Explanation: inline relaxes ODR; the speed decision belongs to the compiler.

2 Complete the inline function

Question
inline int square(int x) { return x * ____; }
Answer
inline int square(int x) { return x * x; }

Explanation: Write return x * x;; inline square computes the square.

3 Match each tool to its role

Term Meaning
inline ODR relaxation
__attribute__((always_inline)) Forced inline
-O0 Inlining off
-O2 Inlining on

All lessons in Expert