Functions

Objectives

  • Create functions to solve problems and modularize programs
  • Send data to functions for processing
  • Use data returned from functions
  • Create function prototypes
  • Discuss variable scope and lifetime
  • Discuss differences between passing by-value vs. by-reference
  • Discuss reference variables
  • Define the term recursion

Functions

  • The basic syntax of a function is
  • if the return data type of a function is void, then you may omit the return statement, otherwise you "must" return a value of the return data type
  • calling a function is easy - just type the function name followed by a list of arguments contained within parentheses (e.g. pow(2.0, 3.0))
  • before an expression using a function is evaluated, the function is called and its returned value is substituted in place of the function call
  • you can write your own functions (actually, you've been writing a main() function for all the C++ programs you've been writing)
  • functions must either be defined before they are used, or there must be a function prototype before the function is used
  • function prototypes look like function definitions, except the function body is missing, and in its place is a semicolon
  • multiple values can be sent to functions through the parameter list
  • only a single value (or none) may be returned by a function
  • a void return data type indicates no value is being returned

Additional function topic outline

  • Variable scope (local vs. global)
  • Duplicate variable names with different scope
  • Variable lifetime
  • Static local variables: retain value between function executions
  • Default arguments: must be rightmost parameters/arguments
  • Overloading functions: same function name, but different formal parameter list
  • Function header, function body, function signature
  • Passing by-value vs. by-reference
  • Reference variables
  • Using a comma-separated list as a return value
  • Signifying global scope using the scope resolution operator (::)

Recursion

Recursion is when a function calls itself either directly or indirectly. We will look at some examples in class.

  • recursion exists to make the programmer's life easier
  • any recursive algorithm can be rewritten using repetition structures
  • recursion usually uses many computer resources such as processing cycles and memory, so iterative alternatives may be preferable if time critical or memory intensive situations
  • testfunc11.cpp: recursive and non-recursive factorial functions
  • testfunc17.cpp: recursive and non-recursive GCD functions
  • testfunc16.cpp: recursive Towers of Hanoi solver

Demonstration programs