Performance
As has been suggested in previous answers, inline
can make code faster, often at the expense of increased executables. However, modern compilers are very good at inlining automatically without any prompt from the user when set to high optimization. Actually, compilers are usually better at determining what to inline for speed gain than humans are.
Declaring functions inline
explicitly for the sake of performance gain is (almost) always unnecessary!
Additionally, compilers can and will ignore the inline
request if it suits them. Compilers will do this if the function is hard to inline (i.e. using nontrivial recursion or function pointers) but also if the function is simply too large to be meaningfully inlined.
One Definition Rule
However, declaring a function inline
may actually be necessary for completely different reasons, namely to satistfy the One Definition Rule (ODR). This rule in the C++ standard states that a given symbol may be declared multiple times but may only be defined once. If the link editor (= linker) encounters several identical symbol definitions, it will generate an error.
One solution to this problem is to make sure that a compilation unit doesn't export a given symbol by marking it static
(static
– the keyword with the most completely unrelated meanings in C).
However, it's often better to mark a function inline
instead. Thus, you allow the compiler to not create the function definition at all. This is often very useful when working with templates which usually have to be declared in header files.
As an example, consider the following program:
// header.hpp
#include <iosfwd> // for std::ostream&
#ifndef HEADER_HPP
#define HEADER_HPP
template <typename IteratorT>
/*inline*/ void print_all(IteratorT begin, IteratorT end, std::ostream& out, char sep = ' ') {
while (begin != end)
out << *begin++ << sep;
}
#endif // !defined(HEADER_HPP)
// test.cpp
#include <iostream>
#include <vector>
#include "header.hpp"
void test_function() {
using namespace std;
vector<int> vec;
int x;
while (cin >> x) vec.push_back(x);
cout << "Results: ";
print_all(vec.begin(), vec.end());
cout << endl;
}
// main.cpp
#include <iostream>
#include <vector>
#include "header.hpp"
void test_function(); // Forward declaration.
int main() {
using namespace std;
vector<int> xyz(23, 42);
print_all(xyz);
cout << endl << "Test call:" << endl;
test_function();
}
Notice that both .cpp
files include the header file and thus the function definition of print_all
. Although the file is saved with include guards against double inclusion, this will result in two definitions of the same function, albeit in different compilation units.
Now, if you try to link those two compilation unit, say, using the following command:
$ g++ -Wall -pedantic main.cpp test.cpp
you'll get an error saying “duplicate definition of print_all
” or something similar. If, however, you unquote the inline
modifier in front of the function definition, the code compiles and links correctly.