Introduction to Functions
- Functions are also sometimes called subroutines, or procedures.
- Functions are really just small programs
- Functions allow us to break the problem into smaller parts.
- This allows us to
- Focus our problem solving on a smaller problem.
- Focus our programming on a smaller problem.
- Focus our debugging on a smaller amount of code.
- Work in groups.
- reuse code.
- We have seen functions all semester
- regular functions:
pow, sqrt, ...
- class member functions:
setw, size, ...
- There is little difference between these, but we will start with regular functions.
- Transferring information to/from functions is done
- via parameters
-
setw(4)
in this case, 4 is a parameter
- or can be a return value
-
rand()
returns an int
- Different functions take different parameters depending on what is to be doe
-
celif
just takes the value you want to find the ceiling of
-
pow
takes both the base and the exponent.
-
find
takes the thing to search for and possibly a starting location.
- When we design a function, we need to know the information we will be
- Passing into the function
- returning from the function
- and possibly sending to the function to be modified.
- The number, type and variability of parameters to a function depend on what the function is doing and what information needs to be transferred.
- A function which takes a string and converts it to upper case would only require a string.
- A function which takes a planet name and returns if it is a valid planet or not would take a string input and produce a boolean output
- A function which plays a guessing game as the guesser would pass no information
- Information is passed into a function in the form of parameters
- A parameter is a variable declared in a function heading.
- Parameters must have a type.
- Parameters can be marked as variable, which means the value can be changed in the function.
- When a function is called, the programmer passes arguments to the function
- There is one argument per parameter
- parameters and arguments are matched by order
- first parameter matches to first argument
- second parameter matches to second argument
- They types of parameters and arguments must match (within coercion)
- The variability must match. (More on this later)
- Parameters (and arguments) vary by function, there is no set requirement other than "What the function needs, produces".
- This makes creating functions somewhat challenging
- The mechanism is different from other syntax we have seen
- It is not static (like a for loop), but depends on the parameters needed.
- It is a system which allows the user to build what they need.