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:
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.