|
|
|
|
|
|
|
lines 23 to 25 the values are swapped, and this action is confirmed by the printout on line 27. Indeed, while in the swap() function, the values are swapped. |
|
|
|
|
|
|
|
|
Execution then returns to line 13, back in main(), where the values are no longer swapped. |
|
|
|
|
|
|
|
|
As you've figured out, the values passed in to the swap() function are passed by value, meaning that copies of the values are made that are local to swap(). These local variables are swapped in lines 23 to 25, but the variables back in main() are unaffected. |
|
|
|
|
|
|
|
|
Later in the book, you'll see alternatives to passing by value that will allow the values in main() to be changed. |
|
|
|
|
|
|
|
|
Functions return a value or return void. void is a signal to the compiler that no value will be returned. |
|
|
|
|
|
|
|
|
To return a value from a function, write the keyword return followed by the value you want to return. The value might itself be an expression that returns a value. For example: |
|
|
|
|
|
|
|
|
return 5;
return (x > 5);
return (MyFunction()); |
|
|
|
|
|
|
|
|
These are all legal return statements, assuming that the function MyFunction() itself returns a value. The value in the second statement return (x > 5), will be zero if x is not greater than 5, or it will be 1. What is returned is the value of the expression, false or true, not the value of x. |
|
|
|
|
|
|
|
|
When the return keyword is encountered, the expression following return is returned as the value of the function. Program execution returns immediately to the calling function, and any statements following the return are not executed. |
|
|
|
|
|
|
|
|
It is legal to have more than one return statement in a single function. However, keep in mind that as soon as a return statement is executed, the function ends. Listing 5.4 illustrates this idea. |
|
|
|
|
|
|
|
|
LISTING 5.4 DEMONSTRATES MULTIPLE RETURN STATEMENTS |
|
|
|
 |
|
|
|
|
1: // Listing 5.4 - demonstrates multiple return
2: // statements
3:
4: #include <iostream.h>
5: |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|