4A. Functions

Functions

You encountered functions when you studied algebra. In general, you use a function in an expression by writing the function name followed by the arguments, in parentheses. The parentheses are required.

In algebra, functions typically have names that are a single letter. C++ supports functions, but their names can have any length. Each argument of a function can be any expression. For example, the value of expression sqrt(9.0 + 16.0) is approximately 5.0.

If there are two or more arguments, separate them by commas. For example, function pow(x, y) produces xy C++ expression pow(2+3, 4/2) has value 25.0.


Evaluating expressions

Evaluate an expression from the inside out. For example, if f (x) = x + 1, then expression f (3+2) + 1 has value 7, computed as follows.

f (3+2) + 1 = f (5) + 1
= 6 + 1
= 7

and

f (4) + f (10) = 5 + f (10)
= 5 + 11
= 16

Terminology: calling a function

An expression that uses a function is referred to as a function call, and we say that expression sqrt(2.0) calls sqrt.


Nested function calls

The argument of a function can be any expression, including an expression that uses a function. For example, if f (x) = x + 1, then

f (f (10)) = f (11)
= 12

and if g(x) = 2*x + 4, then

g(g(7) + f (2)) = g(18 + f (2))
= g(18 + 3)
= g(21)
= 46

Arguments/parameters

If E is an expression and f  is a function, then we say that E is the argument of f  in expression f (E). I will use term parameter interchangeably with argument.



Summary

Expression g(x, y+1) calls function g with first argument x and second argument y+1. g(x, y+1) is an expression, and has a value. For example, function sqrt computes square roots. C++ expression sqrt(36.0) has value 6.0 and
  double q = sqrt(36.0);
declares variable q and stores 6.0 into q.

Exercises

  1. Suppose that g(x) = 3x − 2. What is the value of expression g(g(9) + 1)? Answer

  2. Suppose that g(x) = 3x − 2. What is the value of expression g(g(9 + 1))? Answer

  3. Suppose that g(x) = 3x − 2. What is the value of expression g(g(9)) + 1? Answer