× Home (CS 111) Lectures Assignments Review Ryba's Website

Functions

A function is a block of code with a name. You can jump into a function by calling it, and then return to where you left off. Functions make your program more organized by breaking it down into smaller parts, and they allow you to avoid repeating code. Some functions return a value, and you can think of these function calls as expressions that are evaluated as whatever they return. Some functions take parameters. Execution always begins in the main function.


Function Definitions

img1

Function Calls

In order to call / use a function, you call the function by using the funcation name, followed by () and supplying the needed parameters within.

img2

Functions That Return Values

As stated above, the function call is evaluated as whatever the function returns. The function exits by returning a value, and it must return a value of the correct type.

img3

Void Functions

A function with a return type of void does not return a value. The function exits when you reach either a return statement or the end of the function. Execution then returns to the point right after the function call. A void function does not need to have a return statement.

img4

A void function call may not be part of a larger statement.
HINT** if a function call has an assignment = to its left, the function CANNOT be a return type of void.


Passing Parameters

A function cannot access variables from other functions unless you pass them as parameters. When you call a function, first the parameter expressions are evaluated. Then those values are copied into the function's parameters, which can be used inside the function like variables. Each function call has its own stack frame to store variables and parameters, and modifying them will not affect the variables in other function calls.

img5

Pass By Reference

A reference stores the address of another variable, and you can use it as if it was the original variable. If you pass a parameter by reference, anything you do to that parameter also happens to the original variable. This allows you to modify a variable from inside a function. To pass by reference, add a & next to the parameter in the function header.

img6

Library Functions

Below we call 2 functions from the cmath library. Each function takes a number as a parameter, performs a calculation, and returns the result of the calculation.

img7

Here a function from the C++ standard library to generate a "random" number

img8