On the cppreference page for the inline
specifier, it says,
The
inline
specifier, when used in a function's decl-specifier-seq, declares the function to be an inline function.
An inline function has the following properties:
There may be more than one definition of an inline function in the program as long as each definition appears in a different translation unit and all definitions are identical.
...
Then, a bit down, it says,
The original intent of the
inline
keyword was to serve as an indicator to the optimizer that inline substitution of a function is preferred over function call. ...
Apart from this line, there is no reference to this use of inline
. Is the latter meaning of inline
still valid in the C standards? Or is the latter form deprecated over the former?
If the latter form is still valid, is it worth using it in modern compilers? I have heard that, even though it is the compiler that makes the decision about inlining, using the inline
keyword pushes it a bit. Is this true? Should I use the inline
keyword in my program for this case?
CodePudding user response:
The standard doesn't concern itself with how the assembly is generated, so "inlining" a function can't be mandated in it.
[dcl.inline]/2
words this as a recommendation:
... indicates to the implementation that inline substitution of the function body at the point of call is to be preferred ... An implementation is not required to perform this inline substitution ...
This blog post suggests that GCC and Clang do respect the inline
hint to a certain degree.
Or the latter form is deprecated over the former?
As can be seen in [dcl.inline]/2
, it's not.
I originally wanted to say that they can't deprecate it because they can't mandate it, but they failed to mark their recommendation as "note" (which would mean that it lacks the "standardizing power"), which looks like an editoral error to me.
CodePudding user response:
The inline
keyword makes it possible that all translation units will have access to the definition of a function, which will make it much easier for the compiler to inline the function instead of calling it. So, yes, it does facilitate inlining, though it doesn't (and has never) mandated it.
Should you use the inline
keyword when you want the function to be inlined? Probably not, because you're probably wrong about how that will affect the performance. Note that inlining is still possible across translation units on major compilers if you turn on link time optimizations. So I recommend you do that and leave the rest to the compiler.
Also note that many compilers have extensions to more strongly recommend the compiler to inline a function, like always_inline in GCC. If you're going to use those, I recommend you profile your code before and after to see if you're helping or hurting the performance of your code.