Let say I have an inlined function like this:
inline double CalculateValue() {
// some condition
if (true) {
// some other condition
if (true) {
// another condition
if (true) {
return 1.0;
}
// somethings
std::cout << "inside1" << std::endl;
}
// somethings
std::cout << "inside2" << std::endl;
}
return 2.0;
}
void Process() {
double value = CalculateValue();
value *= 100.0;
std::cout << value << std::endl;
}
int main ()
{
Process();
}
It will "copy and paste" the CalculateValue()
function within the Process()
one. The result is 100
, as expected.
But if I try to emulate how this "copy and paste" will be performed, there's something I don't understand:
void Process() {
double value;
// some condition
if (true) {
// some other condition
if (true) {
// another condition
if (true) {
value = 1.0;
return;
}
// somethings
std::cout << "inside1" << std::endl;
}
// somethings
std::cout << "inside2" << std::endl;
}
value = 2.0;
value *= 100.0;
std::cout << value << std::endl;
}
int main ()
{
Process();
}
Of course when it reaches the return
statement, the rest of the function must be ignored (i.e. inside1
and inside2
must never be printed), because of the return
. But if I return
from the parent function (Process()
), it returns immediately, so I can't ever see 100
.
This means it does it another way.
How does the compiler manage this situation? I tried to create a code block, but still the return
returns to the main function...
While writing your "emulation" you forgot to handle one of the return
s. In an inlined function the compiler would kind of replace it with a goto
statement.
void Process() {
double value;
// begin of inlined function
// some condition
if (true) {
// some other condition
if (true) {
// another condition
if (true) {
value = 1.0;
goto next; // <<<<<<<<<<<<<<<<<<< return replaced by goto
}
// somethings
std::cout << "inside1" << std::endl;
}
// somethings
std::cout << "inside2" << std::endl;
}
value = 2.0;
next:
//end of inlined function
value *= 100.0;
std::cout << value << std::endl;
}