Functions are a different code segment that gets "jumped to". Here's a simplistic example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void sayhi()
{ // when sayhi is "called", the program will run the code in this {code block}
cout << "hi!" << endl;
// when this code block exits, the program "returns" to whatever area of the program
// called the function... as if it never happened.
}
int main()
{
// so we call the function once
sayhi(); // this will execute sayhi's body. Which prints "hi!" to the screen
// once sayhi exits, the program continues here, immediately after the above function call.
// we can even call it again if we want
sayhi(); // (prints another "hi!" to the screen)
}
|
The output of this program would be
Your example is a little more complicated because it's doing 2 extra things:
1) It's passing a parameter to the function (input)
2) It's giving a return value (output)
Parameters let your function act on data "passed to" it.
Return values let your function "return" data out (pass data back to whatever called it).
Here's a simple function that sums two numbers together:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// Return an int
int sum(int a, int b) // take 2 int parameters
{
return a+b; //return the sum of those parameters
}
int main()
{
int foo = 1;
int bar = 2;
// now let's call the sum function to sum foo and bar
int baz = sum(foo,bar);
// when we say =sum(... like that, we are taking the function's return value and assigning
// it to our baz variable.
// as a result...
cout << baz; // this prints "3"
}
|
Simple enough, right? Now here's what your original example is doing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int Mystery (int Location) // take one parameter
{
Location += 2; // add 2 to that parameter
cout << Location // print it <HERE>
<< '\n';
return Location; // and return it
}
int main()
{
int Place = 3;
int Result;
// call the 'Mystery' function with 'Place' as the parameter
// assign the output to 'Result'
//
Result = Mystery (Place);
// here, result is 5 (the output of the Mystery function)
cout << Result; // so this will print "5"
}
|
So why is the 5 printing twice? Because the code is printing it twice!
Remember that the Mystery function
also outputs the value (the line marked <HERE> in the above code). It's being printed
again in main, after Mystery is done. Hence, two prints.
EDIT: doh I'm too slow.