Chapter 6. Return values: getting data from functions

 

This chapter covers

  • Returning information from functions
  • The return keyword
  • Experimenting at the console prompt

In chapter 4 you discovered how functions can increase your efficiency by allowing you to write code once but use it many times. In chapter 5, you made functions much more flexible by passing them information with each call; a function can act in different ways and produce different outputs depending on the arguments you give it. In this chapter you give functions the chance to talk back by returning the results of their work. You also call functions directly at the console prompt to investigate the values they return.

6.1. Returning data from functions

It’s often useful to have a function do some work for you and give you back the result of that work. You can then use the result however you want. In listing 5.6 you saw a showSum function that displays the sum of two numbers on the console. It may be better to have an add function that simply adds the numbers and returns the result. Whereas showSum always displays the result on the console, with add you can display the result the function returns if you choose, use it in further calculations, send it across a network, or save it to a database.

6.1.1. The return value replaces the function call

6.2. Experimenting at the console prompt

6.3. The Crypt—building player information strings

6.4. Summary

sitemap