c++ inline function?
From Wikipedia: Inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.
http://en.wikipedia.org/wiki/Inline_function
On a modern compiler there is likely not much difference. It may be inlined without the inline
and it may not be inlined with the inline
.
Yes there is a difference. https://isocpp.org/wiki/faq/inline-functions.
When you specify that a function is inline you are causing the compiler to put the code of the method in where ever it is being called.
void myfunc() {
square(2);
}
is identical to
void myfunc() {
2 * 2;
}
Calling a function is good for code clarity, but when that function is called the local state has to be pushed to the stack, a new local state is setup for the method, and when it is done the previous state needs to be popped. That is a lot of overhead.
Now if you up your optimization level, the compiler will make decisions like unrolling loops or inlining functions. The compiler is still free to ignore the inline statement.
The former (using inline
) allows you to put that function in a header file, where it can be included in multiple source files. Using inline
makes the identifier in file scope, much like declaring it static
. Without using inline
, you would get a multiple symbol definition error from the linker.
Of course, this is in addition to the hint to the compiler that the function should be compiled inline into where it is used (avoiding a function call overhead). The compiler is not required to act upon the inline
hint.