C++ inline function, parameter passed by value - c++

well last time I checked an inline function is a function whose body is substituted directly in every point in the program where the function is called.
So when I do this :
#include <iostream>
inline void increment(int n) { n = n + 1; }`
int main() {
int n = 0;
increment(n);
std::cout << "Result " << n;
}
I should have : Result 1.
Instead, I get 0.
So how does an inline function work ?

'inline' doesn't replace the text with the function body the way a macro does. It replaces the function call with the EQUIVALENT generated code, so that functionaly it's no different than if it weren't inline.

This is not a problem with it being inline but with the method signature being wrong:
inline void increment(int& n) {
++n;
}
You're asking for a copy, you're getting one. Instead ask for a reference. Don't confuse inline functions with macros, they are not the same. In fact, declaring things inline is usually counter-productive as the compiler will make this call for you depending on your optimization settings.

There are two things you should consider while inlining.
1) Inline is just a request to compiler rather than command to replace the function call with its body so as to avoid overhead related to function calls.
2) You should always inline the functions which are pretty small like getters/setters. Because inlining large functions OR recursive functions lead to code bloat which defeats the purpose of inlining.
Also inline functions have static linkage.

Related

Having trouble when linking the program with undefined symbols [duplicate]

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?
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.
Yes there is a difference. https://isocpp.org/wiki/faq/inline-functions.
When you specify that a function is inline you are causing the compiler to put the code of the method in where ever it is being called.
void myfunc() {
square(2);
}
is identical to
void myfunc() {
2 * 2;
}
Calling a function is good for code clarity, but when that function is called the local state has to be pushed to the stack, a new local state is setup for the method, and when it is done the previous state needs to be popped. That is a lot of overhead.
Now if you up your optimization level, the compiler will make decisions like unrolling loops or inlining functions. The compiler is still free to ignore the inline statement.
From Wikipedia: Inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.
http://en.wikipedia.org/wiki/Inline_function
inline works well with the concept of procedural abstraction:
inline double square (double x) { return x*x;}
int squareTwice(double x) {
double first = square(x);
double second = square(x);
return first * second;
}
The above is fundamentally similar to the following:
int squareTwice(double x) {
double first = x*x;
double second = x*x;
return first * second;
}
This happens because when the compiler inline-expands a function call, the function's code gets inserted into the caller's code stream; therefore, it may be easier to procedurally abstract the second example to the first example.
Procedural abstraction makes it possible to break up a routine into smaller subroutines that are much easier to read (although this can be a style choice).
The inline function, if the compiler complies, will include the inline function in the code in which it was called as if no function was called (as though you had put the logic in the calling function) and avoid the function call overhead.

How the Inline functions having multiple lines of code are treated as a single line?

I have an idea on defining inline functions(normal functions) globally
using "inline keyword" increases performance if the snippet is small.I have
a doubt that :
"how the member functions defined inside classes
also gives the same performance and considered as inline?"
Actually inline functions contain a single line of code
This statement is wrong. There's no such constraint.
Inline function merely means that all the function definition code is placed directly where it is declared.
but member functions defined inside a class contain multiple code instead treated as inline why?
If you're referring to the inline keyword there's also no constraint that functions marked with that keyword can only contain a single line of code.
If it's actually inlined by the compiler (i.e. assembly code directly inserted in place, without a function call) is left to its decision, and mostly depends on compiler optimization strategies chosen in the optimization flags.
You need to provide the inline keyword for non class member functions if they are completely defined in a header file to avoid ODR violation errors.
Here's an example (header file assumed):
class foo {
int x_;
public:
// Inside the class declaration 'inline' is assumed as default
int x() const { return x_; }
int y() const {
int result = 0;
// Do some complicated calculation spanning
// a load of code lines
return result;
}
};
inline int bar() { // inline is required here, otherwise the compiler
// will see multiple definitions of that function
// in every translation unit (.cpp) that includes
// that header file.
return 42;
}
Inline doesn't mean its just single line of code . It means the whole code if it is single line or multiple lines gets inserted at the function calling point thereby reducing function call overhead .
Look at this code, I know it's not C++ but basics are the same.
#include <stdio.h>
#define inlineMacro(x) ((x) = (x) + 1); ((x) = (x) * 2)
int main()
{
int i = 5;
inlineMacro(i);
printf("%i",i);
return 0;
}
Outputs:
12
You can put all of your code on single line. So don't be detracted by keyword inline, it's just for compiler.
I have got a clear explanation from all of you guys.
INTUITION in three 4 points:
1.For normal functions(not methods that are declared /defined in classes) inline keyword is used to interpolate the assembly code (by compiler),thereby avoiding repeating function calls.
2.For methods declared inside classes ,the performance would be same if they are declared as normal functions with inline keyword(no class concept) for a small snippet.
3.method declaration(for classes) is implicit inline.
4.functions declaration is (if needed) is explicit inline.

What the inline function actually do? [duplicate]

This question already has answers here:
When should I write the keyword 'inline' for a function/method?
(16 answers)
Closed 8 years ago.
I was searching the internet a few topics related to inline functions, but none of them took my doubts.
So far I know the inline function works the same way that a method or a block, but recently saw the following response:
By declaring a function inline you tell the compiler to replace the
complete code of that function directly into the place from where it
was called. This is a rather advanced feature that requires
understanding of lower-level programming.
So that means that in normal functions: I was at a point A and wanted to go to point B for that I get out of A and go to B, right?
Have inline functions works in this way: I was at point A and would like to go to point B for that point B comes up to point A?
What I said above is correct?
Ideally, with the inline keyword, the compiler pastes the contents of the inlined function at the point where the function is called.
Given:
void Print(void)
{
cout << "Hello World!\n";
}
int main(void)
{
Print();
return 0;
}
The compiler would emit an assembly instruction to call the Print function inside the main function.
When declaring the Print function as inline, the compiler would generate the conceptual main() function below:
int main(void)
{
// Substitute content of Print function because it's declared as inline
cout << "Hello World!\n";
return 0;
}
Remember that the inline keyword is a suggestion to the compiler and the compiler can ignore it. The compiler may already inline small functions without using the inline keyword.
Long ago, the inline keyword was used to force compilers to paste code where the function was invoked. This technique was used to eliminate function call overhead. This was in the times when compilers were less intelligent about optimizing.
The quote should read "replace the call" ... "place the complete code". The ideal behind an inline function is similar to a macro; in every place in the source code that calls the inline function, instead of calling the inline function, the call is replaced with the complete code from the inline function, and no call is made. This could generate a lot of duplicate code, but should result in faster execution, unless the increase in code size causes issues with cache. In some cases, a compiler may ignore the inline option and use a normal call.
Inline functions is a good tool when you want to save running time because when you call this kind of a function(inline) its code is then written in the call's place. Why does it save time? Because calling a regular function simply consumes more time than just pasting its functionality. Example:
inline void sayHi()
{
std::cout<<"Hi!";
}
int main()
{
sayHi(); //Calling an inline function
std::cin.get();
}
compiler pastes std::cout<<"Hi!"; instead of sayHi();
So what you said is actually correct.

Why I can't define inline member function in another file?

I have three files:
1. Joy.h
class Joy
{
public:
void test();
};
2. Joy.cpp
#include "Joy.h"
inline void Joy::test() {}
3. main.cpp
#include "Joy.h"
int main()
{
Joy r;
r.test();
return 0;
}
I try to compile them using:
g++ cpp Joy.cpp
g++ say:
main.cpp:(.text+0x10): undefined reference to `Joy::test()'
Who can tell me why...
How to solve this problem if I don't want to define that test() function in the .h file and still want it to be an inline function?
when you define an inline member function, you should prepend the member function's definition with the keyword inline, and you put the definition into a header file.
When you declare a function inline basically You are telling the compiler to (if possible)replace the code for calling the function with the contents of the function wherever the function is called. The idea is that the function body is is probably small and calling the function is more overhead than the body of the function itself.
To be able to do this the compiler needs to see the definition while compiling the code which calls the function this essentially means that the definition has to reside in the header because the code which calls the function only has access to the header file.
Good Read:
[9.7] How do you tell the compiler to make a member function inline?
From the standard (N3242, 7.1.2.4):
An inline function shall be defined in every translation unit in which
it is used and shall have exactly the same definition in every case.
Have a look here as well: How do you tell the compiler to make a member function inline?
The compiler needs the complete definition of the function so that it could be inlined where it is called from. That is possible only if you define it in the header itself.
How does inline function work?
Say, you define this:
inline void increment(int &i) { ++i; }
and then use it as:
int i = 0;
while( i < N )
{
std::cout << i << std::endl;
increment(i);
}
then the compiler translates this code into this (roughly speaking):
int i = 0;
while( i < N )
{
std::cout << i << std::endl;
++i; //replaced the call with the equivalent code which the function
//actually executes to produce the same effect
//(edit typo) it replaces to ++i and not i++ as it was the original.
}
Such replacement of function-call with the code of function itself is said to be inlined. You can say, the function is inlined.
Note that the inline keyword is just a hint for the compiler : it tells the compiler if possible inline me. It is not guaranteed that every inline function call will be inlined by the compiler.
Because of the way C++ is compiled in to separate compilation unit (each cpp file typically), the compilation of one cpp file know not of the implmentation of the inlined function in another compilation unit so can't inline it.
The solution is to put the implementation of the inlined function in the header file this way all files using the head have access to the implementation,
an inline function is a function upon which the compiler has been requested to perform inline expansion.
Hence, the whole point of an inline function is that it is implemented in line. There isn't any way to define it in another source file if you still want it to be an inline function.

c++ inline function?

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?
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.
Yes there is a difference. https://isocpp.org/wiki/faq/inline-functions.
When you specify that a function is inline you are causing the compiler to put the code of the method in where ever it is being called.
void myfunc() {
square(2);
}
is identical to
void myfunc() {
2 * 2;
}
Calling a function is good for code clarity, but when that function is called the local state has to be pushed to the stack, a new local state is setup for the method, and when it is done the previous state needs to be popped. That is a lot of overhead.
Now if you up your optimization level, the compiler will make decisions like unrolling loops or inlining functions. The compiler is still free to ignore the inline statement.
From Wikipedia: Inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.
http://en.wikipedia.org/wiki/Inline_function
inline works well with the concept of procedural abstraction:
inline double square (double x) { return x*x;}
int squareTwice(double x) {
double first = square(x);
double second = square(x);
return first * second;
}
The above is fundamentally similar to the following:
int squareTwice(double x) {
double first = x*x;
double second = x*x;
return first * second;
}
This happens because when the compiler inline-expands a function call, the function's code gets inserted into the caller's code stream; therefore, it may be easier to procedurally abstract the second example to the first example.
Procedural abstraction makes it possible to break up a routine into smaller subroutines that are much easier to read (although this can be a style choice).
The inline function, if the compiler complies, will include the inline function in the code in which it was called as if no function was called (as though you had put the logic in the calling function) and avoid the function call overhead.