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 = \frac {1}{2} * (oldguess + \frac {n}{oldguess})\) 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
\(\frac {n}{2}\text{.}\) 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.
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
of
activities on this page.