Functions: Review and Parameter Types
- Function Basics
- Functions are named, parameterized blocks of code (see former lesson's
notes)
- Example: area.cpp and
a.cpp
- Compute the area of a rectangle: area.cpp
- How do we turn the area computation into a function?
- For example: area = computeArea(length, width);
- How do we turn the prompts and corresponding cin statements into
a function?
- For example: length = promptAndGet("Please enter the length");
- Example: functions.cpp
- Function Rules/Restrictions
- Functions must be declared before their first use
- By inclusion (e.g., #include <unistd.h>)
- By prototyping (e.g., void write(int n))
- By actual definition (e.g., void write (int n) { cout << n; })
- Functions are executed when called using the actual parameters
(if any) to initialize the formal parameters (if any)
- This type of parameter semantics is named: Call-by-Value (or Copy
Semantics)
- Next week we'll learn about: Call-by-Reference
- Function may have a return value.
- Formal and actual parameters need not have the same name (but they can)
- Even if the have the same name, they are different variables
- Control Flow
- When a function is called, control of the program proceeds to the
called function where it remains until the called function completes
- Each called function as its own Activation Record
- An Activation Record is (primarily) a listing of the local variables
of the function
- Example: functions.cpp
- Interface Specification
- Calling a Function
- Defining Functions
- Visibility (or Scope)
- Preprocessor
- Used to "include" code from other files or for conditional compilation
- File Inclusion
- Examples:
- #include <filename> - Used for system libraries
- #include "filename" - Used for local libraries
- Conditional Compilation
- #define DefinedVariableName
- Example
- debug.cpp
- To compile without debug code: g++ debug.cpp -o debug
- To compile with debug code: g++ debug.cpp -o debug -DDEBUG
- iostream