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.
Related
I have the below code :
static inline void print(const std::string& value)
{
std::cout<< value <<std::endl;
}
Is the above function really forcing compiler to replace it multiple places?
I want to know whether is it really helpful?
Since this meaning of the keyword inline is non-binding, compilers are
free to use inline substitution for any function that's not marked
inline, and are free to generate function calls to any function marked
inline. Those optimization choices do not change the rules regarding
multiple definitions and shared statics listed above.
Inline reference
The compiler's optimizer is complex and will use heuristics to decide whether to inline code. There are many factors involved in that decision, and use of inline is probably considered. There exist things like MSVC's __forceinline which may give a bigger nudge to that decision but will still not guarantee it.
But in general you can trust the compiler to make the right decision, and functionally there will be no difference to you. You can use recursion, take the address of that function, and the compiler will make it work, inline or not.
The biggest practical difference is what #arnes said:
it permits the functions defined multiple times in different translation units but compiler expects all the definitions are same (otherwise causes undefined behaviour)
C++ allows you to annotate functions with the inline keyword. From what I understand, this provides a hint (but no obligation) to the compiler to inline the function, thereby avoiding the small function calling overhead.
I have some methods which are called so often that they really should be inlined. But inline-annotated functions need to be implemented in the header, so this makes the code less well-arranged. Also, I think that inlining is a compiler optimization that should happen transparently to the programmer where it makes sense.
So, do I have to annotate my functions with inline for inlining to happen, or does GCC figure this out without the annotation when I compile with -O3 or other appropriate optimization flags?
inline being just a suggestion to compiler is not true & is misleading.There are two possible effects of marking a function inline:
Substitution of function definition inline to where the function call was made &
Certain relaxations w.r.t One definition rule, allowing you to define functions in header files.
An compiler may or may not perform #1 but it has to abide to #2. So inline is not just a suggestion.There are some rules which will be applied once function is marked inline.
As a general guideline, do not mark your functions inline just for sake of optimizations. Most modern compilers will perform these optimizations on their own without your help. Mark your functions inline if you wish to include them in header files because it is the only correct way to include a function definition in header file without breaking the ODR.
Common folklore is that gcc always decides on its own (based on some cost heuristics) whether to inline something or not (depending on the compiler/linker options, it can even do so at link time). You can observe this sometimes when using -Winline where gcc warns that an inline hint was ignored, it often even gives a reason.
If you want to know exactly what is going on, you probably have to read the source code of it, or take the word of someone who read it.
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)
C++ ISO standard says, that:
"A function defined within a class definition is an inline function."
Are there any compilers that IGNORE this rule?
(please, do not mistake inline with inlineD - my question is if there is a compiler, that wont put there that inline suggestion that it should)
You seem to be misunderstanding what "inline" means. It doesn't mean functions will automatically be inlined; according to 7.1.2-2 it indicates that inline substitution is to be preferred.
Therefore, you can't tell whether a function is labeled inline or not from the code, since the compiler is free to decide one way or another. It's just a compiler hint.
The standard says that all compilers can ignore inline requests, whether implicit or explicit. Whether or not they do so will nornally depend on whether the function can practically be inlined - for example recursive functions cannot be.
Edit: Just to clarify - the questioner is ignoring this, from the previous para in the standard to that he quoted from:
An implementation is not required to
perform this inline substitution at
the point of call
I suspect your test is flawed. You can't test with only one such file whether the compiler ignores the inline specifier or not.
You need to include the header containing the inline function definition and include it into multiple implementation files that are then linked together. If you get linker errors about multiple defined instances of that functions, then the compiler is ignoring the inline specifier regarding its most important property: Allowing it to be defined multiple times across the entire program while still retaining the same address for it and its local static variables.
What your test probably checks is whether or not the compiler inlines the call to the function, which is actually only a hint to the compiler and only a small of many other more important consequences of the inline specifier. If the compiler does not not inline a call to the function, it is fine doing so. The standard does not require it to do anything in this matter.
See my answer to a very similar question: When is "inline" ineffective? (in C)
Summary: inline is only required to allow multiple definitions. Any function calling changes is purely optional.
Compiler's usually inline based on the number of calls to the function, the number of pseudo-instructions in the function, and a bunch of other things. Take a look at the GCC documentation on optimization options for an idea of how it does things. Basically, the inline keyword is just a hint that bumps up the likelihood that the compiler will inline. The actual decision to inline is usually complex.
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.