6.2. Function Basics

Time: 00:03:20 | Download: Large, Large (CC), Small | Streaming, Streaming (CC) | Slides (PDF)

One easy way to conceptualize a function is as a machine. I often imagine a "wood chipper," one of those machines that take tree limbs, chips them into little pieces, and shoots the chips into the back of a truck. The chipper has an input and an output, and the internal mechanism is enclosed, so we can't see exactly how it does its job - we only know that it does its job because we can see the chips flying into the back of the truck.

Program functions are similar: zero or more inputs and zero or one output. Hopefully, we have some documentation that tells us what the function does, but if we don't have the source code, we can't see exactly how it works. Parameters are the function's inputs, and the return value is its output.

A function represented by a box with inputs at the top and an output on the side. The input can be any valid expression; the output is a single value.
A function as a black box. The illustration conceptualizes a function as a machine with inputs (function parameters), an output (function return value), and the exact implementation hidden inside the body.
An illustration of a function showing that it has a header and a body. The header consists of the return type, the name, and the parameter list enclosed between parentheses.
The parts of a function.
  1. Header (dashed-line box)
    1. Return type
    2. Function name
    3. Parameter list (note that even when empty, the parentheses must be present)
  2. Body - a block enclosed between braces: { and } )

By default, C++ functions implement an argument passing technique called pass-by-value. Pass-by-value means that the inputs are expressions: constants, variables, sub-expressions formed from variables and constants connected with operators, or even other function calls. The program evaluates them and passes the resulting values into the function.

Functions with a void return type don't return anything, but other functions can return a value. Functions that return a value must have at least one return statement. Any valid expression, not just a variable, can follow the return operator. Using the square root function, sqrt, as an example, and assuming that x, y, and z are properly defined and initialized variables, all of the following are valid function calls:

Function call examples. Calls to the sqrt function illustrate how a program evaluates an expression and passes the resulting value to a function. The calls also demonstrate the syntax saving the function's return value in a variable.