7A. Defining Functions


Defining elementary functions

One of the most important features of C++, or of almost any programming language, is your ability to define new functions. You write a large piece of software by breaking it into a collection of small functions, each with a specific purpose.

General form of a function definition

The general form of a function definition is

  R name(arguments)
  {
    body
  }
where

  • R is the type of result that the function yields,

  • Name is the function's name,

  • Arguments is a comma-separated list of the function's arguments. Each argument consists of a type followed by a name.

  • Body is a sequence of statements that performs the actions that the function needs to do.

The part of the definition before the left brace,

  R name(arguments)
is called the function heading. Body is a sequence of zero or more statements that are called the function body. They are performed when the function is called.


The return statement

In the body, statement

  return E;
indicates that the function is finished and that its result is the value of expression E. A function cannot do anything after it performs a return-statement. See return statements for more detail.


Example: successor

Here is a C++ definition of function successor(n) = n + 1. Successor takes one argument of type int and yields, or returns, a result of type int.
  // Successor(n) returns n+1.
  // For example, successor(3) = 4.

  int successor(int n)
  {
    return n+1;
  }

Example: largest

Assume that we have included <algorithm> by writing
  #include <algorithm>
  using namespace std;
Then the following defines function largest so that largest(3, 6, 2) = 6.
  // largest(x, y, z) returns the largest of
  // x, y and z.

  double largest(double x, double y, double z)
  {
    return max(x, max(y, z));
  }

Each argument needs a type

Notice that each argument has a specified type. You are not allowed to write
  double largest(double x, y, z)
  {
    return max(x, max(y, z));
  }
(You might think that would be reasonable, but C++ does not allow it. Stay within the language.)


Exercises

  1. Write a definition of function cube(x), which takes a real number x (type double) and returns x3. You don't need to use pow. Answer

  2. Write a definition of function distance(x1, y1, x2, y2), where all of the arguments are real numbers, and returns the distance between points (x1, y1) and (x2, y2) in the plane. Use the sqrt function. Answer