return?
Sorry guys for my n00by question but what exactly does return do? If I'm writing a fuction and it returns a variable named x what exactly happens to the value of x?
# 1 Re: return?
Be careful with words like "exactly". Someone's liable to start talking stack operations at you.
If a function is executing, it must have been called from somewhere else. When a "return x" statement is reached, the function stops executing and the entire function call expression at the calling location then effectively has the value x.
Thus for a function:
int i_am_six()
{
return 6;
}
then the following statements are identical:
a = 5 + 6;
b = 5 + i_am_six();
There are a number of subtleties, especially once you get pointers involved, but that's something you can worry about later.
# 2 Re: return?
...what exactly happens to the value of x?when you DECLARE that variable, i.e.:
int x;you have told the computer to reserve memory for an variable of integer type and it remembers it's position inside memory
after that call the variable has no defined value
computer now knows that wherever in your code you use x (inside a parenthes scope vhere x is declared) it will go to stored position in memory and give you the value or set it
if you DEFINE a value to x, i.e.:
x = 1;the computer will set stored memory position to 1 and you can use it in your code
(btw. compilers usually warn you about undefined values)
now... for your question...
when the code:
return x;executes, computer will make a copy of x somewhere else in memory, and free memory allocated for variables (it will make it available for someone else to use from now on)
than it will return execution to the position where the function was called and replace that function call with that copy of x from memory
so to answer your question:
The value of x becomes undefined!