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 false if x is not greater than 5, or it will be true. 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.5 illustrates this idea.
Enter a number between 0 and 10,000 to double: 9000 Before doubler is called... input: 9000 doubled: 0 Back from doubler... input: 9000 doubled: 18000 Enter a number between 0 and 10,000 to double: 11000 Before doubler is called... input: 11000 doubled: 0 Back from doubler... input: 11000 doubled: -1
On line 30, in the function Doubler(), the parameter is tested to see whether it is greater than 10,000. If it is not, the function returns twice the original number. If it is greater than 10,000, the function returns -1 as an error value.
The statement on line 34 is never reached, because whether or not the value is greater than 10,000, the function returns before it gets to line 34, on either line 31 or line 33. Many compilers will warn that this statement cannot be executed.
18.188.152.157