Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inlining C++ code

Is there any difference to the following code:

class Foo  
{
  inline int SomeFunc() { return 42; }
  int AnotherFunc() { return 42; }
};

Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the AnotherFunc syntax (accessors for example) but I rarely specify inline directly.

like image 662
Rob Avatar asked Sep 17 '08 19:09

Rob


People also ask

What is inlining in C?

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.

Does C support inline function?

Standard supportC++ 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.

What is inlining a variable?

A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.

What is automatic inlining in C++?

Any function defined within the class definition is automatically declared inline. The length of the function's body doesn't matter for that. Whether the function will actually be inlined in the generated machine code, is an entirely separate and largely unrelated question .


1 Answers

The inline keyword is essentially a hint to the compiler. Using inline doesn't guarantee that your function will be inlined, nor does omitting it guarantee that it won't. You are just letting the compiler know that it might be a good idea to try harder to inline that particular function.

like image 120
Greg Hewgill Avatar answered Nov 15 '22 21:11

Greg Hewgill