Value and Reference Parameters
- Review how to create functions
- Local and Global Scope Rules
- A variable exists from its declaration to the end of its enclosing block
- Variables declared without any block have global scope
- Global variables can be referenced in other source files (demonstrate with
example)
- Variables can be "hidden" by declaring another variable of the same name
- A hidden global variable can be referenced using the scope resolution
operator: ::
- Parameter Types
- Value parameters
- Semantics: The formal parameter gets the value of the actual
parameter (as in an assignment).
- Example:
- Suppose we have the function void print(string s) { cout << s <<
endl; } which we call as print("Hello, World"); within our
program.
- It's as though there is an assignment statement: s =
"Hello, World"; as the first statement in the function.
- Value parameters DO NOT change in the calling function
- Reference Parameters
- Semantics: Rather than passing the value of the actual
parameter, we pass the location (aka address) of the
parameter, so the called function knows how to modify the parameter
directly
- Example:
- Suppose we have the function void print(int &x) { cout << x <<
endl; } which we call as print(var); within our program.
- The "&" before the x means that the function print is
expecting an address, not a value.
- Actual reference parameter arguments MUST be variables (i.e., they cannot be literals)
- Reference parameters MAY have there values changed by the called
function.
- Array are automatically passed by reference
- Example: reference_parms.cpp