< Previous | Contents | Next >

Returning a Value

You can return a value from a function to send information back to the calling code. To return a value, you need to specify a return type and then return a value of that type from the function.


Specifying a Return Type

The first function I declare, askYesNo1(), returns a char value. You can tell this from the function prototype before main():

char askYesNo1();

You can also see this from the function definition after main():

char askYesNo1()

158 Chapter 5 n Functions: Mad Lib


Using the return Statement

askYesNo1() asks the user to enter y or n and keeps asking until he does. Once the user enters a valid character, the function wraps up with the following line, which returns the value of response1.

return response1;

Notice that response1 is a char value. It has to be because thats what I promised to return in both the function prototype and function definition.

A function ends whenever it hits a return statement. Its perfectly acceptable for a function to have more than one return. This just means that the function has several points at which it can end.


Tric k

image

You don’t have to return a value with a return statement. You can use return by itself in a function that returns no value (one that indicates void as its return type) to end the function.

image


Using a Returned Value

In main(), I call the function with the following line, which assigns the return value of the function to answer1.

char answer1 = askYesNo1();

This means that answer1 is assigned either ’y’ or ’n’whichever character the user entered when prompted by askYesNo1().

Next in main(), I display the value of answer1 for all to see.