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.
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.
Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.
Sutter's Guru of the Week #33 answers some of your questions and more.
http://www.gotw.ca/gotw/033.htm
class Foo
{
inline int SomeFunc() { return 42; }
int AnotherFunc() { return 42; }
};
It is correct that both ways are guaranteed to compile the same. However, it is preferable to do neither of these ways. According to the C++ FAQ you should declare it normally inside the class definition, and then define it outside the class definition, inside the header, with the explicit inline keyword. As the FAQ describes, this is because you want to separate the declaration and definition for the readability of others (declaration is equivalent to "what" and definition "how").
Does inline actually make any difference?
Yes, if the compiler grants the inline request, it is vastly different. Think of inlined code as a macro. Everywhere it is called, the function call is replaced with the actual code in the function definition. This can result in code bloat if you inline large functions, but the compiler typically protects you from this by not granting an inline request if the function is too big.
Are there any rules on when you should or shouldn't inline code?
I don't know of any hard+fast rules, but a guideline is to only inline code if it is called often and it is relatively small. Setters and getters are commonly inlined. If it is in an especially performance intensive area of the code, inlining should be considered. Always remember you are trading execution speed for executable size with inlining.
VC++ supports __forceinline and __declspec(noinline) directives if you think you know better than the compiler. Hint: you probably don't!
Inline is a compiler hint and does not force the compiler to inline the code (at least in C++). So the short answer is it's compiler and probably context dependent what will happen in your example. Most good compilers would probably inline both especially due to the obvious optimization of a constant return from both functions.
In general inline is not something you should worry about. It brings the performance benefit of not having to execute machine instructions to generate a stack frame and return control flow. But in all but the most specialized cases I would argue that is trivial.
Inline is important in two cases. One if you are in a real-time environment and not responding fast enough. Two is if code profiling showed a significant bottleneck in a really tight loop (i.e. a subroutine called over and over) then inlining could help.
Specific applications and architectures may also lead you to inlining as an optimization.
I have found some C++ compilers (I.e. SunStudio) complain if the inline is omitted as in
int AnotherFunc() { return 42; }
So I would recommend always using the inline keyword in this case. And don't forget to remove the inline keyword if you later implement the method as an actual function call, this will really mess up linking (in SunStudio 11 and 12 and Borland C++ Builder).
I would suggest making minimal use of inline code because when stepping through code with with a debugger, it will 'step into' the inline code even when using 'step over' command, this can be rather annoying.
Note that outside of a class, inline does something more useful in the code: by forcing (well, sort of) the C++ compiler to generate the code inline at each call to the function, it prevents multiple definitions of the same symbol (the function signature) in different translation units.
So if you inline a non-member function in a header file, and include that in multiple cpp files you don't have the linker yelling at you. If the function is too big for you to suggest inline-ing, do it the C way: declare in header, define in cpp.
This has little to do with whether the code is really inlined: it allows the style of implementation in header, as is common for short member functions.
(I imagine the compiler will be smart if it needs a non-inline rendering of the function, as it is for template functions, but...)
Also to add to what Greg said, when preforming optimization (i.e. inline-ing) the compiler consults not only the key words in the code but also other command line arguments the specify how the compiler should optimize the code.
Related
I know that inline is a hint or request to the compiler and is used to avoid function call overheads.
So, on what basis one can determine whether a function is a candidate for inlining or not?
In which case one should avoid inlining?
Avoiding the cost of a function call is only half the story.
do:
use inline instead of #define
very small functions are good candidates for inline: faster code and smaller executables (more chances to stay in the code cache)
the function is small and called very often
don't:
large functions: leads to larger executables, which significantly impairs performance regardless of the faster execution that results from the calling overhead
inline functions that are I/O bound
the function is seldom used
constructors and destructors: even when empty, the compiler generates code for them
breaking binary compatibility when developing libraries:
inline an existing function
change an inline function or make an inline function non-inline: prior version of the library call the old implementation
when developing a library, in order to make a class extensible in the future you should:
add non-inline virtual destructor even if the body is empty
make all constructors non-inline
write non-inline implementations of the copy constructor and assignment operator unless the class cannot be copied by value
Remember that the inline keyword is a hint to the compiler: the compiler may decide not to inline a function and it can decide to inline functions that were not marked inline in the first place. I generally avoid marking function inline (apart maybe when writing very very small functions).
About performance, the wise approach is (as always) to profile the application, then eventually inline a set of functions representing a bottleneck.
References:
To Inline or Not To Inline
[9] Inline functions
Policies/Binary Compatibility Issues With C++
GotW #33: Inline
Inline Redux
Effective C++ - Item 33: Use inlining judiciously
EDIT: Bjarne Stroustrup, The C++ Programming Language:
A function can be defined to be inline. For example:
inline int fac(int n)
{
return (n < 2) ? 1 : n * fac(n-1);
}
The inline specifier is a hint to the compiler that it should attempt to generate code for a call of fac() inline rather than laying down the code for the function once and then calling through the usual function call mechanism. A clever compiler can generate the constant 720 for a call fac(6). The possibility of mutually recursive inline functions, inline functions that recurse or not depending on input, etc., makes it impossible to guarantee that every call of an inline function is actually inlined. The degree of cleverness of a compiler cannot be legislated, so one compiler might generate 720, another 6 * fac(5), and yet another an un-inlined call fac(6).
To make inlining possible in the absence of unusually clever compilation and linking facilities, the definition–and not just the declaration–of an inline function must be in scope (§9.2). An inline especifier does not affect the semantics of a function. In particular, an inline function still has a unique address and so has static variables (§7.1.2) of an inline function.
EDIT2: ISO-IEC 14882-1998, 7.1.2 Function specifiers
A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.
inline has very little to do with optimization. inline is an instruction to the compiler not to produce an error if the function given definition occurs multiple times in the program and a promise that the definition will occur in every translation that it is used and everywhere it does appear it will have exactly the same definition.
Given the above rules, inline is suitable for short functions whose body doesn't necessitate including extra dependencies over what just a declaration would need. Every time the defintion is encountered it must be parsed and code for its body may be generated so it implies some compiler overhead over a function defined only once in a single source file.
A compiler may inline (i.e. replace a call to the function with code that performs that action of that function) any function call that it chooses. It used to be the case that it "obviously" couldn't inline a function that wasn't declared in the same translation unit as the call but with the increasing use of link time optimization even this isn't true now. Equally true is the fact that functions marked inline may not be inlined.
Telling the compiler to inline a function is an optimization, and the most important rule of optimization is that premature optimization is the root of all evil. Always write clear code (using efficient algorithms), then profile your program and only optimize functions that are taking too long.
If you find a particular function is very short and simple, and it's getting called tens of thousands of times in a tight inner loop, it might be a good candidate.
You might be surprised, though - many C++ compilers will automatically inline small functions for you - and they might ignore your request to inline, too.
Premature optimization is the root of all evil!
As a rule of thumb I usually inline only "getters" and "setters". Once the code is working and is stable, profiling can show which functions could benefit from inlining.
On the other hand, most modern compilers have quite good optimization algorithms, and will inline what you should have inlined for you.
Reasuming -- write inline one-liner functions, and worry about others later.
The best way to find out is to profile your program and mark small functions that get called lots of times and burn through CPU cycles that as inline. The keyword here is "small" - once the function call overhead is negligible compared to the time spent in the function, it's pointless to inline them.
The other use I'd suggest is if you've got small functions that get called in performance critical code often enough to make a cache miss relevant, you should probably inline those as well. Again, it's something the profiler should be able to tell you.
I often use inline functions not as an optimization but to make the code more readable. Sometimes the code itself is shorter and easier to understand than comments, descriptive names etc. For example:
void IncreaseCount() { freeInstancesCnt++; }
The reader immediately knows the complete semantics of the code.
The best way would be to examine and compare the generated instructions for inlined and not inlined. However, it is always safe to omit inline. Using inline could lead to trouble you don't want.
Inline functions might improve your code performance by eliminating the need to push arguments into the stack.
if the function in question is in a critical part of your code you should make the inline not inline decision in the optimization part of your project,
you can read more about inlines in the c++ faq
One should use the inline function qualifier only when the function code is small.If the functions are larger you should prefer the normal functions since the saving in memory space is worth the comparatively small sacrifice in execution speed.
I generally follow a thumb rule where I make a function with 3-4 simple statements as inline. But it is good to remember that it is just a hint to the compiler. The final call to make it inline or not is taken by the compiler only. If there are more than these many statements I will not declare inline as with a stupid compiler it may lead to code bloat.
When deciding on whether to use inline, I usually keep the following idea in mind: On modern machines memory latency can be a bigger bottleneck than raw calculations. Inlining functions that are called often is known to grow the executable size. Furthermore, such a function could be stored in the CPU's code cache which will decrease the number of cache misses when that code needs to be accessed.
Hence, you have to decide for yourself: Does inlining increase or decrease the size of the generated machine code? How likely is it that calling the function will cause a cache miss? If it is peppered throughout the code, then I would say the likelihood is high. If it is restricted to a single tight loop then the likelihood is hopefully low.
I typically use inlining in the cases I list bellow. However, where you are genuinely concerned about performance, profiling is essential. Furthermore, you might want to check whether the compiler actually takes the hint.
Short routines that are called in a tight loop.
Very basic accessors (get / set) and wrapper functions.
Template code in header files unfortunately automatically obtain the inline hint.
Short code that is used like a macro. (E.g. min() / max())
Short math routines.
Also, an inline method has severe side effects when maintaining large projects. When the inline code is changed, all files that use it will be rebuild automatically by the compiler (it it is a good compiler). This could waste a lot of your development time.
When an inline method is transferred to a source file and not inlined any more, the whole project must be rebuilt (at least this has been my experience). And also when methods are converted to inline.
When you think your code is small enough to be used as inline and remember inline function duplicate your code and paste it were the function is called so it may be good enough to increase your execution time but increased memory consumption also.
You can't use inline function when you are using a loop/static variable/recursive/switch/goto/Virtual function.
Virtual means wait until runtime and inline means during compilation so they can't be use simultaneously.
I have read some answers and see that there some stuff missing.
The rule I use is not to use inline, unless I want it to be inline. Looks silly, now explanation.
Compilers are smart enough and short functions always makes inline. And never makes long function as inline, unless programmer said to do that.
I know that inline is a hint or request to compiler
Actually inline is an order for compiler, it has no choices and after inline keyword makes all code inline. So you can never use inline keyword and compiler will design shortest code.
So when to use inline?
To use if you want to have some code inline. I know only one example, because I use it in only one situation. It is user authentication.
For example I have this function:
inline bool ValidUser(const std::string& username, const std::string& password)
{
//here it is quite long function
}
No matter how big this function is I want to have it as inline because it makes my software harder to crack.
for the following function:
inline void A() {
...
B();
...
}
is B also inlined by the compiler?
If not, should I make B inline to increase performance?
In most situations, you can rest comfortably leaving inlining-decisions to the compiler, which will know far better than you when and when not it will result in better performance.
In this specific situation, I would stronlgy suspect that it is completely up to the compiler what to do.
No, the inline keywords will only cause the A code to be inlined inside the caller code. This will not affect inlining of B.
Besides this, in c++, the inline keyword is only a hint to the compiler, which is allowed to ignore it. Modern compilers decide when the functions need to be inlined, even if the keyword is not used.
Somehow all the commenters failed to mention that there are cases when inline is NOT a mere hint to the compiler, but a mandated keyword. It happens when one puts a non-template definition of a function in the header file included by multiple .cpp files. In this case absence of inline will trigger a linker error. As a matter of fact, this is the only case when one should even bother typing those 6 characters. In other cases, compilers will inline everything they can - regardless of this keyword presence.
When you declare a function/method inline, it is just a hint to the compiler that this particular function should be inlined. The compiler then may or may not inline it. The same applies for nested calls like the call to B() inside A().
I would probably add inline specifier to both of the functions, but that's just a matter of style - modern optimizing compiler like GCC will optimize it anyways.
!! Specific on frequently used methods like getter & setter. !!
I have no idea when the keyword inline should be used. Ofc I know what it does, but I still have no idea.
According to an interview with Bjarne Stroustrup he said:
My own rule of thumb is to use inlining (explicitly or implicitly) only for simple one- or two-line functions that I know to be frequently used and unlikely to change much over the years. Things like the size() function for a vector. The best uses of inlining is for function where the body is less code than the function call and return mechanism, so that the inlined function is not only faster than a non-inlined version, but also more compact in the object core: smaller and faster.
But I often read that the compiler automatically inline short functions like getter, setter methods (in this case getting the size() of a vector).
Can anyone help?
Edit:
Coming back to this after years and more experience the high performance C+++ programming, inline can indeed help. Working in the games industry even forceinline sometimes makes a difference, since not all compilers work the same. Some might inline automatically some don't.
My advice is if you work on frameworks, libraries or any heavily used code consider the use of inline, but this is just general advice anyway since you want such code to be fully optimized for any compiler. Always using inline might not be the best, because you'll also need the class definition for this part of the code. Sometimes this can increase compilation times if you can't use forward declarations anymore.
another hint: you can use C++14 auto return type deduction even with seperating the function definition:
MyClass.h
class MyClass
{
int myint;
public:
auto GetInt() const;
}
inline auto MyClass::GetInt() const { return myint; }
all in one .h file.
Actually, inline keyword is not for the compiler anymore, but for the linker.
That is, while inline in function declaration still serves for most compilers as a hint, on high optimization setting they will inline things without inline and won't inline things with inline, if they deem it better for the resulting code.
Where it is still necessary is to mark function symbols as weak and thus circumvent One Definition Rule, which says that in given set of object files you want to make into a binary, each symbol (such as function) shall be present only once.
Bjarne's quote is old. Modern compilers are pretty smart at it.
That said, if you don't use Link Time Code Generation, the compiler must see the code to inline it. For functions used in multiple .cpp files, that means you need to define them in a header. And to circumvent the One Definition Rule in that case, you must define those functions as inline.
Class members defined inside the class are inline by default, though.
The below speaks specifically to C++:
The inline keyword has nothing to do with inlining.
The inline keyword allows the same function to be defined multiple times in the same program:
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.
§3.2 [basic.def.odr]
Attaching meaning beyond this to the inline keyword is erroneous. The compiler is free to inline (or not) anything according to the "as-if rule":
A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input.
§1.9 [intro.execution]
Considering what compiler optimizations can do, the only use of inline I have today is for non-template function whose body is defined inside headers files outside class bodies.
Everything is defined (note: defined != declared) inside class bodies is inline by default, just as templates are.
The meaning of inline in fact is: "Defined in header, potentially imported in multiple sources, just keep just one copy of it" told to the linker.
May be in c++35 someone will finally decide to replace that keyword with another one more meaningful.
C++ standard Section 7.1.2 Point 2:
(...) The inline specifier indicates to the implementation that
inline substitution of the function body at the point of call is to be
preferred to the usual function call mechanism. An implementation
is not required to perform this inline substitution at the point of
call (...)
In other words instead of havin a single code for your function, that is called several times, the compiler may just duplicate your code in the various places the function is called. This avoids the little overhead related to the function call, at the cost of bigger executables.
Be aware that inline keyword may be used also with namespaces, but with a very different meaning. Members of an inline namespace can be used in most respects as though they were members of the enclosing namespace. (see Standard, section 7.3.1 point 8).
Edit:
The google style guide recommends to inline only when a function is ten lines or less.
I'm answering the question my self!: Solution: After a few performance tests, the rule of thumb from Stroustrup is right! inlining Short functions like the .size() from vector can improve the performance (.size() calls are used frequently). But the impact is only noticeable for FREQUENTLY used functions. If a getter/setter method is used a lot, inlining it might increase the performance.
Stroustrup:
Don’t make statements about “efficiency” of code without first doing
time measurements. Guesses about performance are most unreliable.
I have the following class defined in a foo.h header file
class Foo {
public:
inline int Method();
};
inline int Foo::Method() { // Implementation }
I would like now to move the implementation to a foo.cpp file. To this end, I have to remove the inline keyword and move the implementation of the method to a foo.cpp file like this
#include `foo.h`
inline int Foo::Method() { // Implementation }
I have two questions:
Is my statement about the removal of the inline keyword correct? Should it be necessarily removed?
How typically the removal of the inline keyword affect the performance (practically all my methods are inlined)?
Thank you very much in advance.
If you moved the function definition from a header to a cpp file, you MUST remove the inline keyword all all locations for that function. With older linkers it might make things slightly slower, but with modern linkers you should notice no real difference in performance.*
There are certain cases where a public member function can be inline, but that's just a bad idea. Don't do it. Arguments can be made for marking certain private member functions as inline, but in reality what you really want in those to be __attribute__((always_inline)) or __forceinline
*In extremely rare cases it will make a difference, but 99% of the time it won't, and 99.9% of what's left you don't care. If measurements show you hit that one-in-ten-thousand, you can use the aformentioned __forceinline.
Keyword inline is redundant in the class. It is implied if you have a function body.
In the implementation file it is also fairly redundant.
The only use of it is if you define a free function in a header (or a member function outside the class, but in the header) to avoid multiple bodies.
Optimization-wise on mist modern compilers it's even more redundant, they inline anything in sight without question anyway, or ignore your keyword at will.
The inline usage must be consistent! From 7.1.2p4:
An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. —end note ] If the definition of a function appears in a translation unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is
declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. ...
You, and the people here giving advice about small functions, are looking at inline the old-fashioned way.
inline used to mean "I want this code to run quickly, so whenever I call this function, I want you to expand it in-place to avoid the overhead of a function call."
That's a really good optimization. It's so good, in fact, that the compiler will eagerly do it even if you don't specify inline.
The compiler is also free to not expand your inline functions. So you really don't have to worry about how it will affect performance, because the compiler can and will ignore inline if you use it in a stupid way.
In fact, compilers today almost always ignore your use of inline, and just do whatever they think is best.
So, knowing that, why do people still use inline?
There's only one reason to use inline nowadays, and that's to work around the One Definition Rule (ODR).
In C/C++, you're only allowed to define a function once. If you do this:
int foo() { /* do something */ }
int foo() { /* do something else */ }
the compiler will complain that you've defined the same function twice.
That looks like a silly example, but it's particularly easy to do something like that when you're using #include - if you defined your function in a header, and you #include the same header twice, this is exactly what you're doing.
Thankfully, inline has another use which is still valid today: if you mark a function as inline, it forces the compiler to silence ODR issues, making it possible to define your function in a header.
In other words, inline now means "I want to define this function in a header."
When you look at it that way, it should be clear that you should remove the inline when moving the function into a cpp file.
For interest sake, there's a couple places where functions are implicitly made inline. One of them is in class member functions:
struct Foo {
void bar() { /* do something */ }
};
I've seen people mark functions like this inline, but that's completely redundant. The compiler does it anyway; there's no need to worry about ODR, and there's no performance to be gained.
The other place is in templates. Since templates have to be defined in headers, they're exempt from the ODR, and inlineing them is redundant.
If the function isn't TINY (or takes several arguments, but doesn't do much, such as a constructor or similar, that takes a bunch of things, and just copies it to somewhere inside the class), inlining it will have little impact on performance in the first place. Setters and getters are usually good candidates to inline, since they (typically) just copy data from one place to another, and can easily be done where the call takes place.
As others have said, it's a "please compiler, if I may ask you kindly, consider inlining this function" - it's not a "make this function inline". The compiler, on the other hand, will often inline functions REGARDLESS of whether there is an inline keyword. It looks at the size of the function, the number of calls and how much larger the code gets from inlining.
If you move the function to "foo.cpp", it will ONLY get inline inside the "foo.cpp" compile unit (typically, compile unit = source file).
That is unless you have a compiler capable of "whole program optimization" or similar tricks, and enable that feature - this basically means that instead of producing a ready to link object file with machine code, the compiler produces a "parsed, but not completely translated to machine instructions" object file. Then, when it comes to finally putting the executable (or shared library) toegether, the compiler/linker will produce one large lump of machine code from the "halfway" code. Both MS and GCC do support this, but I don't know how well it works for large projects.
Edit:
As per Mooing Duck's comment: An inline function doesn't make a real function name in the object file, so the linker may also give errors for unresolved symbol int Foo::Method() [or some wording to that extent].
End edit.
If performance is critical, you should measure the current code's performance, then make your changes, and measure it again. If it's significantly different, you'll have your answer. If it's faster (because of less inlining leading to more cache-hit rate for other bits of code, for example), then that's good. If it's slower, you'll have to put back (some of) the functions into the header file. Or live with it being slower... Or find some other way of making it faster again... The choices are yours (and, if you work in a group, some other people may have a say in the final decision, of course). It's almost impossible for anyone to say for SURE which way it will go without at the very least understanding the whole programs architecture and what goes on in the class - which, given the name "foo.cpp" in the post is probably not the REAL code...
It may be confusing, but you should not think of the purpose of inline to make the compiler inline a function. (Modern compilers are way smarter than you in regards to when a function should be inlined or not anyway).
No, the real purpose of inline is to tell the linker to not worry about multiple definitions of the function. If you put the definition of a (non-member) function in a header, you should mark it inline to avoid linker errors.
2. How typically the removal of the inline keyword affect the performance (practically all my methods are inlined)?
The inline keyword tells the compiler to take the implementation code of that function and put it in place of the function call. This reduces the number of function calls on the stack and if used correctly, can improve the performance of your program.
The inline keyword should only be used with small functions. Get and Set functions are good examples. They set the value of one variable or return the value of one variable.
If you make a function with a lot of code inline, it can increase the size of your code by a lot (depending on the size of the function code and how many times that function is used) and actually DECREASE the performance of your program.
In C++, do methods only get inlined if they are explicitly declared inline (or defined in a header file), or are compilers allowed to inline methods as they see fit?
The inline keyword really just tells the linker (or tells the compiler to tell the linker) that multiple identical definitions of the same function are not an error. You'll need it if you want to define a function in a header, or you will get "multiple definition" errors from the linker, if the header is included in more than one compilation unit.
The rationale for choosing inline as the keyword seems to be that the only reason why one would want to define a (non-template) function in a header is so it could be inlined by the compiler. The compiler cannot inline a function call, unless it has the full definition. If the function is not defined in the header, the compiler only has the declaration and cannot inline the function even if it wanted to.
Nowadays, I've heard, it's not only the compiler that optimizes the code, but the linker can do that as well. A linker could (if they don't do it already) inline function calls even if the function wasn't defined in the same compilation unit.
And it's probably not a good idea to define functions larger than perhaps a single line in the header if at all (bad for compile time, and should the large function be inlined, it might lead to bloat and worse performance).
Yes, the compiler can inline code even if it's not explicitly declared as inline.
Basically, as long as the semantics are not changed, the compiler can virtually do anything it wants to the generated code. The standard does not force anything special on the generated code.
Compilers might inline any function or might not inline it. They are allowed to use the inline decoration as a hint for this decision, but they're also allowed to ignore it.
Also note that class member functions have an implicit inline decoration if they are defined right in the class definition.
Compilers may ignore your inline declaration. It is basically used by the compiler as a hint in order decide whether or not to do so. Compilers are not obligated to inline something that is marked inline, or to not inline something that isn't. Basically you're at the mercy of your compiler and the optimization level you choose.
If I'm not mistaken, when optimizations are turned on, the compiler will inline any suitable routine or method.
Text from IBM information Center,
Using the inline specifier is only a
suggestion to the compiler that an
inline expansion can be performed; the
compiler is free to ignore the
suggestion.
C Language Any function, with the exception of main, can be declared or
defined as inline with the inline
function specifier. Static local
variables are not allowed to be
defined within the body of an inline
function.
C++ functions implemented inside of a class declaration are
automatically defined inline. Regular
C++ functions and member functions
declared outside of a class
declaration, with the exception of
main, can be declared or defined as
inline with the inline function
specifier. Static locals and string
literals defined within the body of an
inline function are treated as the
same object across translation units;
Your compiler's documentation should tell you since it is implementation dependent. For example, GCC according to its manual never inlines any code unless optimisation is applied.
If the compiler does not inline the code, the inline keyword will have the same effect as static, and each compilation unit that calls the code will have its own copy. A smart linker may reduce these to a single copy.
The compiler can inline whatever it wants in case inlining doesn't violate the code semantics and it can reach the function code. It can also inline selectively - do inline when it feels it's a good idea and not inline when it doesn't feel it's a good idea or when it would violate the code semantics.
Some compilers can do inlining even if the function is in another translation unit - that's called link-time code generation.
Typical cases of when inlining would violate code semantics are virtual calls and passing a function address into another function or storing it.
Compiler optimize as he wants unless you spec the opposite.
The inline keyword is just a request to the compiler. The compiler reserves the right to make or not make a function inline. One of the major factor that drives the compiler's decision is the simplicity of code(not many loops)
Member functions are declared inline by default.(The compiler decides here also)
These are not hard and fast rules. It varies according to the compiler implementations.
If anybody knows other factors involved, please post.
Some of the situations where inline expansion may NOT work are:
For functions returning values, if a loop, a switch, or a goto exists
For function not returning values, if a return statement exits;
If functions contain static variables
If inline functions are recursive.
Inline expansion makes a program run faster because the overhead of a function call and return statement is eliminated. However, it makes the program to take up more memory because the statements that define the inline functions are reproduced at each point where the function is called. So, a trade-off becomes necessary.
(As given in one of my OOP books)