Skip to main content

Section 4.1 Defining C++ Functions

In general, we can hide the details of any computation by defining a function. A function definition requires a name, a group of parameters, a return type, and a body. It may either return a variable, value, or nothing (specified by the keyword void). For example, the simple function defined below returns an integer which is the double of the value you pass into it.
The syntax for this function definition includes the name, timesTwo, and a parenthesized list of formal parameters and their types. For this function an int named num is the only formal parameter, which suggests that timesTwo needs only one piece of data to do its work. The details, hidden “inside the box,” simply compute the result of num*2 and return it. We can invoke or call the timesTwo function by asking the C++ to evaluate it, passing an actual parameter value, in this case, 3. Note that the call to timesTwo returns an integer that can in turn be passed to another invocation.
Let us look at a similar function.
The timesTwoVoid function behaves very similarly to timesTwo. However, there is one key difference between them. Instead of the int in timesTwo, timesTwoVoid has a void in front of its function definition. Unlike timesTwo, timesTwoVoid is a non-fruitful function meaning it does not return a value even though it can still print something out.
We could go a step further and implement our own square root function by using a well-known technique called “Newton’s Method.” Newton’s Method for approximating square roots performs an iterative computation that converges on the correct value. The equation newguess=12(oldguess+noldguess) takes a value n and repeatedly guesses the square root by making each newguess the oldguess in the subsequent iteration. The initial guess used here is n2. Listing 1  shows a function definition that accepts a value n and returns the square root of n after making 20 guesses. Again, the details of Newton’s Method are hidden inside the function definition and the user does not have to know anything about the implementation to use the function for its intended purpose. Listing 1  also shows the use of the // characters as a comment marker. Any characters that follow the // on a line are ignored.
Listing 1

Reading Questions Reading Question

1.

What is the correct return type of the function above int main()?
  • void
  • Correct, nothing is returned!
  • int
  • Not quite, check the value preceding the name of the function!
  • dog
  • Not quite, dog is not even a data type!
  • dogWalk
  • Not quite, that is the name of the function itself!
You have attempted 1 of 6 activities on this page.