More in depth explaination of inline funcs?

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.
Last edited on
Does the compiler "choose" at that point to just not inline the function?
Yes, the keyword "inline" is a hint for the compiler. It is completely up to the compiler what to do with this hint.

For free functions the inline keyword tells the compiler that the function appears only once, even if the body is defined within the header.

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?
An expression that appears once within your code will not mysteriously multiplied. There is no reason for that.

If the function remains inline, how is the memory allocated?
What memory allocation. An inline substitution might look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

void inline add(int &x) {
	x++;
}

int main(void) {
	int x = 0;
	for (int a = 0;a < 10;a++) {
		add(x);
{
	x++;
}
		std::cout << x << std::endl;
	}
	std::cin >> x; // To keep it from closing
	return 0;
}
That is much simpler that I was imagining; your example really clears it up for me. I appreciate your time, thank you for the answer.
Topic archived. No new replies allowed.