classes

Pages: 12
return does 2 things:

1. it jumps to the end of the function
2. it pushes the return value on the stack

after a function returns the stack is unwinded. means: the space on the stack (local variables) is discarded with 1 exception: the return value.

the caller function knows that the called function left a return value on the stack and may assign that returned value to one of its variables. The function itself is always done at that moment
A function is not like a variable in the way a variable holds data. Its return value is what the function call ultimately evaluates to.

Lets say you write this piece of code:

 
x = (2 * 5) - (8 - 1);


When the program reaches this line, it reads (2 * 5) and evaluates it as 10. After that, it reads (8 - 1) and evaluates it as 7. Finally, it evaluates 10 - 7 as 3, and assigns that value to the variable x.

With a function, it works like this:

1
2
3
4
5
6
7
8
int sum()
{
	int a = 5 + 2;

	return a;
}

x = sum();


Here, when the program reaches the line x = sum() (where the function sum gets called) and executes it. In it, the function's variable 'a' gets assigned the number 7. The line return a; means that ultimately the function call sum() evaluates to 7, which is of the type int.

Here's an example of a void funtion:

1
2
3
4
5
6
7
8
9
10
11
12
int aGlobalVariable = 10;

cout << aGlobalVariable << endl;	// prints out 10

void DuplicateValue()
{
	aGlobalVariable *= 2;
}

DuplicateValue();

cout << aGlobalVariable << endl;	// prints out 20 


Hope that helped out.
Sorry its took this long to reply, that helped alot, thanks :)
Topic archived. No new replies allowed.
Pages: 12