Title: Functions Parameters
1Functions Parameters Variable Scope
Chapter 6
2Overview
- Using Function Arguments and Parameters
- Differences between Value Parameters and
Reference Parameters - Using Local Variables in a Function
- Function Preconditions and Postconditions
- Testing a program
- Stubs
- Drivers
- Variable Scope and Duration
3Functions
- Every C program must have a main function
- execution starts by looking for a main
- All other functions are called directly from
main, or indirectly through a chain of function
called from main - Function Calls
- One function calls another by using the name of
the called function next to ( ) enclosing an
argument list. - ex. strlen(FirstName)
- A function call temporarily transfers control
from the calling function to the called function.
4 Argument in Calling Block
25
4000
age
- Value Parameter Reference Parameter
The value (25) of the argument is passed to the
function when it is called.
The memory address (4000) of the argument is
passed to the function when it is called.
In this case, the argument can be a variable
identifier, constant, or expression.
In this case, the argument must be a
variable identifier.
5Weve been using value parameters
- Simple types (like int, char, float, double) are
value parameters by default - you can specify reference parameters with
- To create a reference parameter you need to place
an after the type in the both function heading
and prototype. - void Cube(int x)
6When to Use Reference Parameters
- If you want your function to
- Assign a value to a variable from where it was
called - Change the value of a variable permanently
- Using a Reference Parameter
- is like giving someone the key to your home
- the key can be used by the other person to change
the contents of your home!
7- If you pass only a copy of 25 to a function, it
is called pass-by-value and the function will
not be able to change the contents of age. It is
still 25 when control returns from the function.
8BUT, if you pass 4000, the address of age to a
function, it is called pass-by-reference and
the function will be able to change the contents
of age. It could be 23 or 90 when you return.
9Example Pass-by-Reference
- We want to find 2 real roots for a quadratic
equation with coefficients a,b,c. Write a
prototype for a bool function named GetRoots( )
with 5 parameters. - Return value is true if real roots exist, false
otherwise - The first 3 (value) parameters are type float.
The last 2 are reference parameters of type
float. - Need to pass 2 values back
10GetRoots prototype
- Bool GetRoots(float, float, float, float,
float) - This function uses 3 incoming values
- It calculates 2 outgoing values, returning the 2
real roots of the quadratic equation with
coefficients a, b, c
11Function Definition
bool GetRoots( float a, float b, float c,
float root1, float root2) float temp //
local variable temp b b - 4.0 a c
if (temp lt 0) return false else
root1 (-b sqrt(temp))/(2.0 a)
root2 (-b - sqrt(temp))/(2.0 a)
return true
12- include ltiostreamgt
- include ltcmathgt
- void GetRoots(float, float, float, float,
float) - using namespace std
-
- void main ( )
- float c1, c2, c3, first, second
- int count 0
- ...
- while ( count lt 5 )
- cin gtgt c1 gtgt c2 gtgt c3
- if (GetRoots(c1, c2, c3, first, second))
- cout ltlt first ltlt second ltlt endl
- else
- cout ltlt "No real solution"
- count
-
- ...
13Data Flow ? Passing Mechanism
- Parameter Data Flow Passing-Mechanism
Incoming / in / Pass-by-value Outgoi
ng / out / Pass-by-reference Incoming
/outgoing Pass-by-reference /
inout /
14Questions
- Why use functions?
- To abstract away unneeded detail
- To allow for easy, accurate updates
- To allow easy reuse of code
- Can a function even call itself?
- Yes, that is called recursion
- It is very useful and requires special care in
writing
15Functions with reference parameters
- Write a prototype and function definition for a
void function called GetRating( ) with one
reference parameter of type char - The function repeatedly prompts the user to
enter a character at the keyboard until one of
these has been entered E, G, A, P - The inputs stand for Excellent, Good, Average,
Poor
16void GetRating( char ) // prototype
- void GetRating (char letter)
-
- cout ltlt Enter employee rating. ltlt endl
- cout ltlt Use E, G, A, or P
- cin gtgt letter
- while ((letter ! 'E') (letter ! 'G')
- (letter ! 'A') (letter ! 'P'))
-
- cout ltlt "Invalid. Enter again "
- cin gtgt letter
-
17Drivers and Stubs
- When building a large project, it is sometimes
helpful to test each function in isolation - This allows the programmer to test a single
function before the entire program is written - The function to be tested must be called
- A simple main function, called a driver, can call
the function with appropriate arguments - The function to be tested might call other
functions which have not yet been implemented - Use functions which match the signature of these,
but which do no real work, are called stubs
18- include ltiostreamgt
- void GetRating( char ) //prototype
- using namespace std
- int main( )
- char rating rating 'X'
- GetRating(rating) // call
- cout ltlt "That was rating "
- ltlt rating ltlt endl return 0
19Preconditions and Postconditions
- the precondition is an assertion describing
everything that the function requires to be true
at the moment the function is invoked - the postcondition describes the state at the
moment the function finishes executing - the caller is responsible for ensuring the
precondition, and the function code must ensure
the postcondition
FOR EXAMPLE . . .
20Function with Postconditions
- void GetRating ( / out / char letter)
- //Precondition None
- //Postcondition User has been prompted to enter
a char, - //and letter one of these input values E,G,A,
or P -
- cout ltlt "Enter employee rating. Use E, G, A,
or P " - cin gtgt letter
- while ((letter ! E) (letter ! G)
(letter ! A) (letter ! P) ) -
- cout ltlt Rating invalid. Enter again
- cin gtgt letter
-
21Function with Pre Post conditions
- void GetRoots( / in / float a, / in /
float b, / in / float c, / out /
float root1, / out / float root2 ) - // Precondition a, b, and c are assigned
- // a ! 0 bb - 4ac ! 0
- // Postcondition root1 and root2 are
assigned - // root1 and root2 are roots of quadratic
with coefficients a, b, c -
- float temp
- temp b b - 4.0 a c
- root1 (-b sqrt(temp) ) / ( 2.0 a )
- root2 (-b - sqrt(temp) ) / ( 2.0 a )
- return
22Function with Pre Post conditions
- void Swap
- (
- /inout/ int firstInt,
- /inout/ int secondInt
- )
- //PreconditionfirstInt secondInt initialized
- //Postcondition the values stored in firstInt
- //and secondInt are swapped
-
- int temporaryInt
- temporaryInt firstInt
- firstInt secondInt
- secondInt temporaryInt
-
23Using a Parameter Passing Mechanism
- Pass-by-Reference
- use only if the design of the called function
requires that it be able to modify the value of
the parameter - Pass-by-Constant-Reference
- use if the called function has no need to modify
the value of the parameter, but the parameter is
very large - use as a safety net to guarantee that the called
function cannot be written in a way that would
modify the value passed in - Pass-by-Value
- use when none of the reasons given above apply
- pass-by-value is safer than pass-by-reference
24More About VariablesStorage Duration Scope
- We are familiar with some variable attributes
- name, type , value
- Two other important attributes of a variable
- storage duration (lifetime)
- the period during which the variable exists in
memory - scope (visibility)
- the portion of program where the variable can be
referenced
25More About VariablesStorage Duration in C/C
- C/C provides 2 kinds of storage duration
- Automatic storage duration
- Static storage duration
26More About VariablesAutomatic Storage Duration
- Variable of automatic storage duration ...
- is created when block in which it is declared is
entered - exists while block is active
- is destroyed when block is exited
- A function's local variables, ...
- i.e., those declared in parameter list or in
function body - normally have automatic storage duration
27More About VariablesAutomatic Storage Duration
- Keyword auto
- auto explicitly declares automatic (storage
duration) variables - For example, following declaration
- auto float x, y
- indicates that float variables x y are
automatic local variables they exist only in
body of function in which declaration appears - Local variables have automatic storage duration
by default - Because of this, keyword auto is rarely used
- Automatic storage is a means of conserving
computer memory because automatic variables exist
only when they are needed
28More About VariablesStatic Storage Duration
- Static variables exist when program begins
execution - Storage for static variables is allocated when
program begins execution is initialized only
once - Although variables of static storage duration
exist from start of program execution, this
doesn't mean that they can be referenced
throughout the program - storage duration versus scope (lifetime versus
visibility) - Two types of variables with static storage
duration - global variables
- static local variables
29More About Variables Static Storage Duration
- A global variable ...
- is created by declaring it outside of any
function definition - retains its value throughout execution of program
- can be referenced by all functions that follow
its declaration - A static local variable ...
- is created by declaring a local variable with
keyword static - e.g. static int counter
- retains its value when function in which it is
declared is exited - when function is called again, variable has value
it had when the function last exited - is visible only in the function in which it is
declared (just like automatic variables)
30More About Variables Static Storage Duration
- Note on Use of Global Variables
- Declaring variable as global rather than local
allows unintended side effects to occur ... - such as when a function that does not need access
to the variable modifies it, accidentally or
maliciously - In general, use of global variables should be
avoided - except in certain unique situations (usually
associated with some kind of performance
requirements)
31More About VariablesScope
- The scope of a variable is the portion of a
program in which the variable can be referenced - For example, when we declare a local variable in
a block, it can be referenced only in that block
or in blocks nested within that block - Storage duration of an variable does not affect
its scope - Two important types of scope for C/C variables
- file scope
- block scope
32More About VariablesScope
- Variables with file scope
- Variables declared outside any function have file
scope - Known in all functions from point at which
variables are declared until end of file - Global variables have file scope
- Variable with block scope
- Variables declared inside blocks have block scope
- Function parameters local variables declared
with functions have block scope - When blocks are nested, a variable in an outer
block has same name as another in an inner block,
variable in outer block is "hidden" until inner
block terminates
33More About VariablesScope
void function1() // prototype for function1 void
function2() // prototype for function2 int
x0 // global to entire program int
main(void) int x1 // local to
main ... int x2 // global to function1
function2 void function1() int x1, x3 //
local to function1 ... void function2() int
x0 //local to function2 ...
34More About VariablesStatic Local Variable Example
// program illustrating use of static
variable include ltiostreamgt Using namespace
std void StaticExample(int) // function
prototype int main() StaticExample(1) // 1st
call to function StaticExample(2) // 2nd call
to function StaticExample(3) // 3rd call to
function return(0) void StaticExample(int
i) static int count 0 cout ltlt "count
coming in (call " ltlt i ltlt ") is " ltlt
count ltlt endl count cout ltlt "count
going out (call " ltlt i ltlt ") is " ltlt
count ltlt endl
(output)
count coming in (call 1) is 0 count going out
(call 1) is 1 count coming in (call 2) is
1 count going out (call 2) is 2 count coming in
(call 3) is 2 count going out (call 3) is 3
how would output be different if count is not
declared static?
35Detailed Scope Rules
- Function names have global scope
- Function parameter scope is identical to scope of
a local variable declared in the outermost block
of the function body. - Global variable (or global constant) scope
extends from declaration to the end of the file,
except as noted below - Local variable (or local constant) scope extends
from declaration to the end of the block where
declared - This scope includes any nested blocks, except as
noted below - An identifiers scope does not include any nested
block that contains a locally declared identifier
with the same name - Local identifiers have name precedence
- The local identifier obscures the other identifier
36Name Precedence
- When an expression refers to an identifier, the
compiler first checks the local declarations - If the identifier isnt local, compiler works
outward through each level of nesting until it
finds an identifier with same name - Any identifier with the same name declared at a
level further out is never reached - If compiler reaches global declarations and still
cant find the identifier, an error message
results
37Namespace Scope
- The scope of an identifier declared in a
namespace definition - extends from the point of declaration to the end
of the namespace body - includes the scope of any using directive
specifying that namespace - Hence the "using namespace std" statement adds
our program to the scope of the identifiers
declared in the standard libraries
38What is the scope of each variable?
- int someInt
- int Square (int n)
-
- int result
- result n n
- return result
-
39Arguments for Reference Parameters
- Reference parameters change the contents of the
original argument - reference parameter arguments must be a
variables - not expressions
- Value parameters can have arbitrary expressions
for their arguments