Persistence of local variables in memory after end of function scope?
If, for example, I have a small function:
int sum(int a, int b)
{
int result = a+b;
return result;
}
Here, the result
is a local variable which, from what I understand, should live only for the execution time of the function. How is the caller of this function able to retrieve the return value of the sum() function, which is nothing but the value of the local variable result
? Just wanted to know how values of local variables declared inside a function are returned back to the caller functions. I know this happens in the stack but I wanted to know how exactly how it happens.
return result;
doesn't return the result
variable, it returns the value of the result
variable. So it's fine that result
goes away when the function returns, all we need is its value.
Return values are frequently put in registers rather than the stack, but may be pushed on the stack in some architectures. This page on the cdecl call style gives a good overview. Note that the details vary by calling convention and platform.
But the key point is still the first paragraph: It's the value of result
, not result
, that the caller receives.
You pass variables values, not variables. In this way you can pass value directly eg sum(8)
.
Everything is implementation specific, but you can assume that calling result = sum(myValueOne, myValueTwo);
function looks in this way (of course it's a lie :) ):
myValueOne
value to register myValueTwo
value to other register result
variable You can see it better on the example below:
void increment(int a)
{
a++;
}
int main(void)
{
int a =7;
increment(a);
printf("My number is now: %dn", a); /* Will print 7 */
return 0;
}
And you are right about variable scope. Here you are the illustration of the wrong function:
int* increment(int a)
{
int b;
b = a+1;
return &b;
}
It returns pointer to (address of) local variable and of course it's wrong, because this variable doesn't exist after function exit. Anyway compiler shall return at least warning in this case.
Cheers, Mikolaj
There is a question Where in memory are my variables stored in c? which says about how things are stored in the computer so local variables is stored in the stack and globals is stored in data
链接地址: http://www.djcxy.com/p/82494.html上一篇: C程序中变量的地址
下一篇: 函数作用域结束后内存中局部变量的持久性?