COSC 1337 - Programming Fundamentals II


Example C++ Programs
Chapter 6 - Functions

Topics covered

Program

Data

Getting a result from a function

There are two mechanisms in C++ for getting a result back from a function. These are:

  • the function return value
  • a reference parameter

These mechanisms are independent of each other. They can be used together in the same functions (for example, a function that returns one result using the function return value and passing another result through a reference parameter). But in many cases it is best to avoid mixing these mechanisms in one function. So for now I would recommend that you follow these suggestions:

  • If a function has no results to "return", use a void function.
  • If a function has one result to "return", you have a choice. You can use a value-returning function and use the return statement to return the result. Or you can use a void function with a reference parameter to pass the result back.
  • If a function has multiple results to "return", use a void function with a reference parameter for each result.
This example program includes a function that returns no results (printCost()), a function that returns one result (calcCost()) and a function that returns two results (getItemInfo()).

ch6_calc_cost.cpp

 

 


Creative Commons License
© Austin Community College 2016. The content on this page is licensed under a
Creative Commons Attribution 4.0 International License.
Last updated: February 18, 2016