I am in the process of learning C++ and I have come to learning inline functions. I know their purpose and when to/not to use them, but I don't completely understand how they fundamentally work and I'm hoping some of you may.
As far as I understand it, instead of reusing the same memory whenever a function is invoked and executing the prologue and epilogue wrapped around the function's code, the compiler just places the full function code wherever it is invoked (basically allocating space for each call instead of reusing the same memory).
I understand that this increases the total size of the compiled program, but what about a program that does not know how many times the function will be called prior to compilation? Does the compiler "choose" at that point to just not inline the function? If the function remains inline, how is the memory allocated?
Example of a code that can execute until you input -1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
void inline add(int &x) {
x++;
}
int main(void) {
int x = 0;
for (int a = 0;a != -1;) {
std::cin >> a;
add(x);
std::cout << x << std::endl;
}
return 0;
}
|
Also, for loops of a defined size like in the following example, does the compiler store the same function over ten times or still only once?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
void inline add(int &x) {
x++;
}
int main(void) {
int x = 0;
for (int a = 0;a < 10;a++) {
add(x);
std::cout << x << std::endl;
}
std::cin >> x; // To keep it from closing
return 0;
}
|
In advance, thank you for your time. I use the term "invoke" and "call" interchangeably. If they are not synonymous I apologize.