I was reading the C++ fAQ book and in chapter 9 the book starts talking about inline functions. The book says that inline functions are way to optimize your code?
I have no idea what is this inline function so could someone explain to me in the most easiest way as possible:
1.What is inline function(and of course explain what does the inline keyword itself do!)?
3.Why should i use it and when?
4.Mauby little code example?
Normally when the compiler calls a function, it pushes the function paramters to a stack, then jumps to a different area of the program which has the code for that function. Then when the function is done it jumps back and pops all that stuff off the stack.
When a compiler "inlines" a function, it doesn't do any of that. Instead the compiler sort of takes the code for the function body and "copy/pastes" it into the code that calls it.
Pros:
- avoids overhead of pushing/jumping to another section of code
- allows for other optimizations because the inlined function can be optimized in hand with the calling code
Cons:
- can inflate the size of (and thereby potentially slow down) your program by repeating the same code over and over.
The inline keyword just tells the compiler "Hey, this function might be a good one to inline."
thank you for answering! so did I understand this correctly:
so here's the code before running the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
usingnamespace std;
inlineint random(int c){
c++;
return c;
}
int main()
{
int b=6;
int x= random(b); //calling the inline function..
cout <<x << endl;
}
And here's what the code would like while running the program:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<iostream>
usingnamespace std;
int main()
{
int b=6;
int x= b++; //calling the inline function.. (mauby not exactly like this but you get the idea...)
cout <<x << endl;
}
The compiler would likely inline it to something like this as a first step:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int b = 6;
// the function inlined
int random_return_val;
{
int c = b;
c++;
random_return_val = c;
}
int x = random_return_val;
cout << x << endl;
}
Which would then likely get optimized to this:
1 2 3 4 5 6
int main()
{
int b = 6;
int x = (b + 1);
cout << x << endl;
}
(or even this):
1 2 3 4
int main()
{
cout << 7 << endl;
}
Note in none of these cases is 'b' ever modified, because the original random function doesn't modify 'b'.