Alex
Alex

Reputation: 671

Do inline functions retain their context within the function they are inlined within

If I create a function which is declared as inline, and use that within another function, if the function is inlined (which may not happen, as inline is optional for the compiler), would that function retain it's own context scope?

i.e. would the inlined function's stack variables disappear from the stack at the end of the inserted inlined function, or after the function it has been inserted into has been taken off the stack?

Upvotes: 0

Views: 287

Answers (1)

Pete Becker
Pete Becker

Reputation: 76245

Whether or not stack variables exist outside their scope is not "observable behavior". That is, a conforming program cannot detect whether their memory still exists. So, under the "as if" rule, the compiler is free to leave the memory their, reuse it for some other variable, or pop the stack. Your program can't tell, and all three of those can be seen if you look at the generated machine code.

Even without inlining the compiler will often play with memory in ways that might not be obvious.

void f() {
    int a = get_a_value();
    call_a_function(a);
    int b = get_b_value();
    call_another_function(b);
}

Here, chances are good that when you compile with optimizations, the compiler will use the same memory location for a and b. Formally they have the same lifetime, but their actual uses do not overlap, so there's no need for separate memory locations. (And, yes, it's also possible that the compiler would just stuff the data into a register rather than using memory).

Again: if your program can't tell the difference, the compiler can do whatever makes sense for the hardware and OS.

Upvotes: 3

Related Questions