6A. Functions

You should be familiar with functions from algebra. For example, if f (x) = 2x, then f (6) = 12.

You can use functions in C++ expressions. But function names are not limited to one letter. For example, one function that is available is called sqrt; if variable x has already been declared, then

  double row = 2*sqrt(x + 1.0);
declares variable row  and stores 2√x+1 into row. The parentheses around the argument, x + 1.0 here, are required.


Terminology

We say that expression sqrt(x + 1.0) calls the sqrt function. "Call" is another name for "use", in the special case of using a function.

In expression sqrt(x + 1.0), we say that the value of x + 1.0 is passed to sqrt.

I will use terms argument and parameter interchangeably for a value that is passed to a function. For example, in expression 2*sqrt(x + 1.0), the argument (or parameter) of function sqrt is x + 1.0.


Functions with more than one argument

If a function has two or more arguments, separate the arguments by commas. For example, we will see function max(x, y), which yields the maximum of two values. Statement

  int m = max(22,35);
declares variable m and stores 35 into it.


Functions without parameters

If function f  has no parameters, call f  by writing an empty pair of parentheses after f . For example, there is a predefined function function called random that takes no parameters and returns a (psuedo-)random integer from 0 to 2147483647. (It returns a value of type long, which is like int, but on some computers allows larger numbers than type int.) The following declares r and stores a (pseudo-)random integer into r.

  long r = random();


Exercises

  1. Suppose f (x) = 3x+1. What is the value of f (f (3))? Answer