Reputation: 1999
Following is a simple function definition that returns an integer
int myFunc()
{
int localVar = 99;
return localVar;
}
and it called in main as
int main()
{
int y = myFunc();
cout << y << endl;
return 0;
}
This works as it is expected. I want to know why?
localVar
is a local variable and its value is allocated in stack. It goes out of scope as soon as the function ends. So, localVar
would have gone out of scope in the call int y = myFunc();
How/Why is it still able to return the correct value?
Upvotes: 2
Views: 125
Reputation: 110738
There are three things to be aware of here:
localVar
myFunc
y
Yes, localVar
goes out of scope at the end of myFunc
. However, before that happens, its value is being copied into the return value of myFunc
(that's what the return
statement does). Then, this return value is being copied into the object y
. It doesn't matter that localVar
is now gone - you have a copy of it.
That's exactly what returning by value does. It copies the result of the expression in the return
statement into a return value.
Upvotes: 2
Reputation: 887877
Your function is returning a copy of the value – that's what "return by value" means.
int y = myFunc();
will copy the bytes of the value from a temporary location used by the function invocation to your local variable.
It would only fail if you return the address of the local variable.
Upvotes: 6
Reputation: 23226
Because of the return
type of your function: int myFunc()
. It allows you to pass back an int
value. The variable localVar is indeed out of scope in main(), but localVar is not being used there, y is, and when used as y = myFunc()
, it accepts the int value returned.
Upvotes: 0
Reputation: 15185
localVar
must not be generated on the stack. If a register is available it could be used also.
If it was in fact created on the stack then the value is copied to a register anyway on returning.
Upvotes: 0