Why should i do something like this:
inline double square (double x) { return x*x;}
instead of
double square (double x) { return x*x;}
Is there a difference?
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
Standard support. C++ and C99, but not its predecessors K&R C and C89, have support for inline functions, though with different semantics. In both cases, inline does not force inlining; the compiler is free to choose not to inline the function at all, or only in some cases.
The inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. Using inline functions can make your program faster because they eliminate the overhead associated with function calls.
Functions that are present inside a class are implicitly inline. Functions that are present outside class are considered normal functions.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With