Objectives
•Function and Parameter Declarations
•Returning a Single Value
•Returning Multiple Values
•Applications
•Variable Scope
Objectives (continued)
•Variable Storage Category
•Common Programming Errors
Function and Parameter Declarations
•A function is called by using function’s name and passing data as arguments
Function and Parameter Declarations (continued)
•Function prototype: declaration statement for a function; it specifies
–Type of value that will be returned (if any)
–Data type and order of arguments that must be supplied when calling it
Syntax:
returnDataType functionName(list of argument data types);
Function and Parameter Declarations (continued)
•Function prototype allows
–Error checking of data types by compiler
–Conversion of all arguments passed in to the required data type
•When a function is called, the arguments must be passed in the correct order, type, and number
Function and Parameter Declarations (continued)
Function and Parameter Declarations (continued)
•Function declaration consists of two parts:
–Function header: identifies the data type of the return value, and specifies number, type, and order of arguments
–Function body: set of statements that operates on the data passed in as arguments
•Arguments: also called formal parameters
Function and Parameter Declarations (continued)
Function and Parameter Declarations (continued)
•Function body: constant and variable declarations, and statements, contained in braces
Syntax:
{
symbolic constant declarations,
variable declarations, and
other C++ statements
}
Function and Parameter Declarations (continued)
•Stub: placeholder for a function not yet written
•Stubbed functions allow testing of main() function logic without all of the details
•A function may be declared with no arguments; it is invoked simply by its name
•Default argument values may be specified for use if a value is not passed in when function is invoked
Function and Parameter Declarations (continued)
Function and Parameter Declarations (continued)
Function and Parameter Declarations (continued)
Function and Parameter Declarations (continued)
Returning a Single Value
Returning a Single Value (continued)
•return statement: causes the value to be returned to the calling function
Syntax: return expression;
•return statement should use data type specified in function header
•Calling function must assign the called function to a variable of the same data type as the called function’s return type
Returning a Single Value (continued)
Returning a Single Value (continued)
•When a function is called, a stack region for the function must be built by the operating system
•If function is small and not called often, the overhead of calling this function may not be efficient
•inline function: a function whose code is placed by the compiler directly inline at the point at which it is called
•inline function must be placed ahead of any calls to it
Returning a Single Value (continued)
Returning Multiple Values
Returning Multiple Values (continued)
•Reference parameter declaration in function header uses the addressof operator
Syntax: dataType& referenceName
Returning Multiple Values (continued)
Returning Multiple Values (continued)
Applications
•Problem-Solver Algorithm consists of three tasks, each of which can be implemented as a function:
–Get inputs
–Calculate result
–Display result
•Rectangular to Polar Coordinate Conversion:
–Convert rectangular (x,y) coordinates to polar form (r, theta)
Applications (continued)
•Simulation:
–Simulate the tossing of a coin to determine the number of resulting heads and tails
–Pseudorandom numbers: numbers that are sufficiently random (the order cannot be predicted)
–rand() function generates pseudorandom numbers; srand() sets the initial random “seed” value
–Scaling: adjusting the range of numbers
Variable Scope
Variable Scope (continued)
Variable Scope (continued)
Variable Scope (continued)
Variable Scope (continued)
Variable Scope (continued)
Variable Scope (continued)
•Use of global variables and constants should be restricted to only those that must be shared among several functions
•Function prototypes, however, typically are global
Variable Storage Category
•Lifetime of a variable: the timeframe within which a variable exists (has memory storage)
•Storage category of a variable: determines where and how long the storage location is kept
•Four storage categories:
–auto
–static
–extern
–register
Variable Storage Category (continued)
•Storage category placed before the data type in the declaration
Syntax:
storageCategory dataType variableName;
•Local variables can be members of only the auto, static, or register storage classes
•Default storage class is auto
•auto: local variable storage is created on entrance to the function, and released on exit
Variable Storage Category (continued)
Variable Storage Category (continued)
•static: once created, local static variables remain and retain their values for the life of the program
•Static variables are created and initialized during compilation
•Static variables can be initialized by constants or constant expressions only; they are set to zero if no explicit initialization value is given
Variable Storage Category (continued)
Variable Storage Category (continued)
•register: variables have the same time duration as auto, but are stored in registers, not normal memory storage
•register storage can increase performance, but is platform dependent; compilers may switch register storage variables to auto storage
•Cannot use the address operator & with register storage; registers do not have standard memory addresses
Variable Storage Category (continued)
•Global variables cannot be declared as auto or register, but may be static or extern
•static and extern affect only the scope, not the time duration, of the variable
•extern: extends the scope of a global variable; a global variable declared in one file may be used by another file
•extern declaration does not cause the creation of a variable by reserving new storage
Variable Storage Category (continued)
Variable Storage Category (continued)
•Global static variables cannot be extended to a second file using the extern declaration
•Global static variables are declared in the same way as local static variables, but outside of any functions
Common Programming Errors
•Passing incorrect data types to a function
•Assuming a change to a local variable in the called function also changes another local variable of the same name in the calling function
•Assuming a change to a local variable also changes a global variable of the same name
•Omitting the called function’s prototype before or within the calling function
Common Programming Errors (continued)
•Terminating function’s header line with a semicolon (creating a null statement)
•Omitting data type for function parameters in header line
Summary
Summary (continued)
Summary (continued)
•Storage category of a variable determines how long the value will be retained:
–auto: variable is created when the function is entered and destroyed when the function is exited
–register: stored in a computer’s internal registers instead of memory
–static: variable retains its values for the duration of the program
Objectives
•Basic Loop Structures
•while Loops
•Interactive while Loops
•for loops
•Loop Programming Techniques
Objectives (continued)
•Nested Loops
•do while Loops
•Common Programming Errors
Basic Loop Structures
•Repetition structure has four required elements:
–Repetition statement
–Condition to be evaluated
–Initial value for the condition
–Loop termination
•Repetition statements include
–while
–for
–do while
Basic Loop Structures (continued)
•The condition can be tested
–At the beginning: pretest or entrance-controlled loop
–At the end: posttest or exit-controlled loop
•Something in the loop body must cause the condition to change, to avoid an infinite loop, which never terminates
while Loops
while Loops (continued)
while Loops (continued)
Interactive while Loops
Interactive while Loops (continued)
Interactive while Loops (continued)
Interactive while Loops (continued)
•break statement: forces an immediate break, or exit, from switch, while, for, and do-while statements
•break statement violates pure structured programming, but is useful for breaking out of loops when an unusual condition is detected
Interactive while Loops (continued)
Interactive while Loops (continued)
•continue statement: applies to while, do-while, and for statements; causes the next iteration of the loop to begin immediately
•continue statement is useful for skipping over data that should not be processed in this iteration, while staying within the loop
•Null statement: a semicolon with nothing preceding it; a do-nothing statement required for syntax purposes only
for Loops
for Loops (continued)
•Altering list: provides the increment value that is added or subtracted from the counter in each iteration of the loop
•If initializing list is missing, the counter initial value must be provided prior to entering the for loop
•If altering list is missing, the counter must be altered in the loop body
•Omitting the expression will result in an infinite loop
for Loops (continued)
for Loops (continued)
Loop Programming Techniques
•These techniques are suitable for pretest loops (for and while):
–Interactive Input within a Loop
•Includes a cin statement within a while or for loop
–Selection within a Loop
•Using a for or while loop to cycle through a set of values to select those values that meet some criteria
Loop Programming Techniques (continued)
Loop Programming Techniques (continued)
Loop Programming Techniques (continued)
Loop Programming Techniques (continued)
–Interactive Loop Control
•Variable is used to control the loop repetitions
•Provides more flexibility at run-time
Loop Programming Techniques (continued)
Nested Loops
•Nested loop: a loop contained within another loop
–All statements of the inner loop must be completely contained within the outer loop; no overlap allowed
–Different variables must be used to control each loop
–For each single iteration of the outer loop, the inner loop runs through all of its iterations
Nested Loops (continued)
Nested Loops (continued)
do while Loops
•do while loop is a posttest loop
–Loop continues while the condition is true
–Condition is tested at the end of the loop
Syntax:
do
statement;
while (expression);
•All statements are executed at least once in a posttest loop
do while Loops (continued)
do while Loops: Validity Checks
•Useful in filtering user-entered input and providing data validation checks
•Can enhance with if-else statement
Common Programming Errors
•Making the “off by one” error: loop executes one too many or one too few times
•Using the assignment operator (=) instead of the equality comparison operator (==) in the condition expression
•Testing for equality with floating-point or double-precision operands; use an epsilon value instead
Common Programming Errors (continued)
•Placing a semicolon at the end of the for clause, which produces a null loop body
•Using commas instead of semicolons to separate items in the for statement
•Omitting the final semicolon in a do statement
Summary
Summary (continued)