chapter 9 functions
Post on 31-Dec-2015
24 Views
Preview:
DESCRIPTION
TRANSCRIPT
Chapter 9
Functions
9.1 What are Functions?
Functions - group of related statements that perform a specific task or job
Terminology:• Function header: Start of the function• Function call: Act of invoking the function• Parameters: Variables that provide information
to a function• Return: A value returned from a function
9.1 What are Functions?Functions can be treated as a “black box”
Black box - implies we can regard this function as a standalone unit
With predefined functions, don’t need to understand its implementation - just its purpose
Inputs OutputMagic
HappensHere
9.1.1 Advantages & Disadvantages
Advantages of functions• Modularization aids in the process of step-wise
refinement
• By breaking code into individual components it becomes easier to maintain and understand by others
• Focusing energies in a specific area results in a shorter time to find and correct errors
9.1.1 Advantages and Disadvantages
Advantages of functions (continued)• Once written, that code can be used again
simply by calling
• Provides the ability of many programmers all writing key functions and integrating these functions into a working and cohesive project
9.1.1 Advantages and Disadvantages
Other function characteristics:• Calling a function has a little cost in relation to
performance
• When called, flow of the program is transferred to that function
• When completed, control returns to where the function was called
9.1.1 Advantages and Disadvantages
How does the computer know where to go back to and how does it maintain the state of all of the variables when the function was called?
• This information is saved prior to the flow being transferred to the function and restored when control is returned to the calling function
9.1.1 Advantages and Disadvantages• Because of overhead costs, don’t write
functions that are one or two lines long unless it is going to be reused repeatedly
• If short and not going to be called again, the overhead would be detrimental to the program’s performance
• Expense of using functions is minor in comparison to the benefits they provide (saving developer time in debugging, maintaining, and extending the code)
9.1.2 What About main?
• Takes on the role of the director
• Controls flow of the program - and little else
• Always the entry point
9.1.2 What About main?
• May have a conditional, a loop, and function calls, but that is about it
• Includes a minimum of processing
• Physically place main as the first function within your source code
9.2 Function Components
Three components to every function (including predefined functions): • Declaration
• Definition (body)
• Call
9.2 Function Components
Two of the predefined function components, the declaration and definition, are hidden• Declaration exists in the header files
• Definition is in the C++ library
Third component - function call - provided by the programmer to invoke the function
9.2.1 Function Declaration
Function declaration - provides compiler with information so it can verify the existence of the function name and the required parameters
Function prototype and function declaration often used interchangeably in C++
9.2.1 Function Declaration
• Should be placed above main making them global
• Provides each function the ability to call any other function
Syntax:
<return-type> <function-name> ( <parameter-list> );
9.2.1 Function Declaration
<return-type> specifies data type of value returned from the function
• If no value returned, the function must be specified as void
•void - in C and C++ literally means nothing
9.2.1 Function Declaration
<function-name> represents a valid identifier name• Must adhere to all naming rules as defined for
variable names
• Function name should begin with a strong verb signifying what task the function will perform (read, write, calculate, etc.)
9.2.1 Function Declaration
<parameter-list> represents a comma delimited list of the variables passed to the function
• If no parameters are passed to the function, place the void keyword in the parentheses OR to leave the parentheses empty
9.2.1 Function Declaration
// Returns nothing, is passed nothingvoid DisplayMenu();
// Returns nothing, is passed nothingvoid PrintInstructions( void );
// Returns an integer and is passed nothingint ReadData();
// Returns an integer and is passed two integersint FindMaximum( int value1, int value2 );
// Returns nothing, passed a float, a double and a boolvoid DisplayResults( float, double, bool );
9.2.2 Function Definition
Function definition - defines what the function doesTwo components
1. Function header 2. Function body
Function header - start of the function definition• Exactly like the function declaration, minus semicolon
Function body - statements that will be executed when the function is invoked
9.2.2 Function Definition
When a function body has finished program flow is returned to the place where the function was invoked
// Returns nothing, is passed nothingvoid PrintInstructions()// Function header-notice no ‘;’{// Beginning of function body cout << "Staple your loan application.\n"; cout << "In addition, sign your form!\n\n"; cout << "\t\t\t ***** Have a great day ****";}// End of function body
9.2.2 Function Definition
Must be placed outside of any other function
Syntactically incorrect to define a function within another function
9.2.3 Function Call
Function call - transfers control of the program to a specific function
If a function returns a value, immediately assign it to a variable or use it in an expression -- if not, it will be lost
9.2.3 Function Call
// Function returns no valuePrintInstructions();
// Function returns an integercout << "Maximum number is: " << FindMaximum( val_1, val_2 ); // Function returns an integerint max_value = FindMaximum( val_1, val_2 );
// Returns an integer but value is never usedFindMaximum( val_1, val_2 );
9.3 return
All predefined math functions gave a value back after doing the calculations ( i.e., function returned a value)
In both the function header and declaration a return type other than void specifies the function will return a value
9.3 return
return - immediately ends execution of the function and sends the value back to where it was called
bool DisplayLogoffMsg( bool done ){ cout << "Staple all pages of your application.\n"; cout << "In addition date and sign your form!\n\n"; if ( done ) return true; else return false; // Unreachable code! cout << "\t\t * Have a great day *\n\n"; cout << "\t\t\t\t ** Logged off **"; }
9.3 return
If a function returns a value, all paths through the function must have a return statement
bool DetermineHonorRollStatus(){ double gpa = 2.4; if ( gpa > 3.50 ) { cout << "Excellent Work" << endl; return true; } else if ( gpa >= 3.0 ) { // Will produce compiler warning: Not all control paths // return a value cout << "Nice job" << endl; } else { cout << "Keep Trying" << endl; return false; }}
9.3 return
Considered poor style to place a return in the body of a loop
Can be used without an actual value to return• Generally used to abnormally terminate the
function
• Avoid both of these usages of the return
9.3 return
int SumTheValues() { int sum = 0, value = 0; for ( int i = 0; i < 5; i++ ) { cout << "Enter value " << i + 1 << ": "; cin >> value;
sum += value; } return sum;}
9.3 returnNot necessary to return a value from a
function• Without a return the function will end anyway
• Flow transfers back to where called from when last statement in the body has executed
• Signature of this type of function will have void as its return type
9.4 Passing Parameters
Passing a value or parameter - giving a value to a function• Calling function provides information to the
called function
• Value sent is placed within the function call’s parentheses
9.4 Passing Parameters
Example passing two values to the pow function
double base = 3.0, power = 4.0, exponent;
...
exponent = pow( base, power ); // Calling pow function
9.4 Passing Parameters
Every value in the call has a corresponding value in the function header and declaration• First parameter caught in the first parameter in
the header
• Second parameter caught in the second parameter and so on
• Data types of parameters must all match
9.4 Passing Parameters
Order of parameters determines where values go - not the name of individual parameters • Could call function foo and pass the values a, b, and c
• In the function header, you could catch those values as x, y, and z
9.4 Passing parameters
// Declaration/Prototypeint CalculateBoxVolume( int len, int wid, int h );
int main(){ int length = 3, width = 4; ... // Call int box_vol = CalculateBoxVolume( length, width, 2 ); ... return 0;}// Definitionint CalculateBoxVolume( int len, int width, int height ) { return len * width * height;}
9.4.1 Formal and Actual Parameters
Formal parameters appear in function header
Actual parameters appear in function call
Names of actual parameters do not have to match names in function prototype or the formal parameters - but the data types should match
9.4.2 Scope
Scope - refers to where within a program an identifier can be seen
Local variables - variables declared within the body of a specific function• Visibility is only within that particular function
• Lifetime limited to only that function
Global variables - variable declared outside of any function
9.4.3 Passing by Value
Passing by value - a copy of the value is made and passed to the function• Function manipulates the copy, not the original
• When called function is done, function's actual parameter retains original value
9.4.3 Passing by Value
// Includes and constants. . .// Prototype int CalcDays( int age );int main(){ int age = 20; int days = 0; days = CalcDays( age ); . . . return 0;}
// CalcDays functionint CalcDays( int age ){ int days; // Since Ralph lied about // his age age += 35; days= age * DAYS_IN_YEAR; return days;}
Addresses
20 0
age days
1000 1004
main Before Call
55 20075
age* days*
2000 2004
20 20075
age days
1000 1004* Values after calculations
CalcDays main After Call
9.4.3 Passing by Value
Following functions have all of their parameters passed by value
double CalcAverage( double first_val, double second_val );
int FindTestTotal( int test1, int test2, int test3 );
char FindLetterGrade( int overall_score );
9.4.4 Passing by Reference
Passing by reference - pass an alias that directly references the variable• Changes made to formal parameter are
reflected in the actual parameter when the function is done
• To pass by reference place an ampersand (&) after the formal parameter’s data type
9.4.4 Passing by Reference
// Includes and constants. . .// Prototype int CalcDays( int & age );int main(){ int age = 20; int days = 0; days = CalcDays( age ); . . . return 0;}
// CalcDays functionint CalcDays( int & age ){ int days; // Since Ralph lied about // his age age += 35; days= age * DAYS_IN_YEAR; return days;}
20 0
age days
1000 1004
main Before Call
20075
age* days*
2000 2004
* Values after calculations
CalcDays
55 20075
age days
1000 1004
main After Call
Addresses
9.4.4 Passing by Reference
Following example passes parameters both by value and by reference
// Two parameters passed by referencevoid Swap( int & a, int & b );
// Two parameters passed by value, one by referencevoid FindAverage( double a, double b, double &average );
// Two parameters passed by referenceint EnterData( int &id, char &code );
9.4.4 Passing by Reference
Use only if the original value needs to be changed• Use pass by value for all other occasions
Regardless how arguments are passed into the function, the call statement remains the same
9.5 Default Arguments
Default argument - value the programmer provides that will automatically be inserted if no value is provided for that specific parameter in the function call
Two types of arguments or parameters: mandatory and default
9.5 Default Arguments
Mandatory arguments - must be specified in the function call• Mandatory arguments must come before any
default arguments in the parameter list
9.5 Default Arguments
Default arguments - provided starting with the rightmost variable in parameter list
Default values can continue from right to left, but once stopped, can not start again later
9.5 Default Arguments
Put default values only in the function declaration or prototype - do NOT include them in the function header
9.5 Default Arguments
// Function declarations ONLYvoid DisplayMenu( int times = 1 );void PrintInstructions( int length, int height = 7 );int ReadData( int &records, double units = 45.5, int size = 11 );
// Examples of different calling optionsDisplayMenu( times );DisplayMenu();DisplayMenu( 3 );PrintInstructins( 5, 10 );PrintInstructions( 7 );ReadData( records );ReadData( records, 50.5 );ReadData( records, 50.2, 11 );
9.6 Putting It All Together
// Chapter 9 - Section 9.6// Filename: Example9_6_1#include <iostream>#include <cmath>using std::cout;using std::endl;int Fun1( int a, int b );void Fun2( int & a, int b );void Fun3( int & c, int & d );void PrintOutput( int a, int b );int main(){ int a = 2, b = 10; PrintOutput( a, b ); a = Fun1( a, b ); cout << a << "\t" << b << endl; Fun2( a, b ); PrintOutput( a, b ); return 0;}void PrintOutput( int a, int b ){ cout << a << "\t" << b << endl;}
int Fun1( int a, int b ){ int c; c = a + b; a++; --b; cout << a << "\t" << b << "\t" << c << endl;
return c;}void Fun2( int & a, int b ){ a += 5; double temp = pow(static_cast<double>(a),2); b = static_cast<int>( temp ); PrintOutput( a, b ); Fun3( a, b ); PrintOutput( a, b );}void Fun3( int & c, int & d ){ c = 25; d = 10; PrintOutput( c, d );}
9.6 Putting It All Together
// Output
2 10
3 9 12
12 10
17 289
25 10
25 10
25 10
9.7 Debugging - Call Stack
Call Stack window - allows viewing where in the hierarchy of function calls the current line of execution is located
Also shows values of each of the parameters passed to the function
9.7 Debugging - Call Stack
To view the Call Stack window while debugging access the following menu items• Debug -> Windows -> Call Stack• OR – Ctrl + Alt + C (to display Call Stack
window)
9.7 Debugging - Call Stack
From Call Stack window
Can see there are other functions that called main • Responsible for displaying the console window• Also for loading the program into memory
9.8 More Predefined Functions
Chapter 6 discussed some of the predefined mathematical functions
The following functions manipulate individual characters
9.8.1 Character CaseTo change the case of a single character
Function declarations•int toupper( int c );•int tolower( int c );
These functions are passed an integer by value and return an integer
Don’t forget ASCII values
Can pass a character and catch it as an integer because this would be a widening conversion - no type casting is needed
9.8.1 Character Case
To use toupper and tolower - include <cctype>
#include <cctype>...char again;
cout << "\nDo you wish to multiply two numbers (y/n)? ";cin >> again;
// Notice the function callwhile ( toupper( again ) == 'Y' ) { ... cout << "\n wish to multiply two more numbers (y/n)? "; cin >> again;}
9.8.1 Character Case
Parameters passed to the toupper and tolower functions were passed by value - original parameter is not changed
Converted value is returned
Like mathematical functions, toupper and tolower are not in a namespace
9.8.2 The “is” Functions
Group of functions to test characters to determine what classification the character fits into• Example: ispunct - determines if the
character is punctuation
• All have the following syntax:
int <is-function>( int c );
9.8.2 The “is” Functions
The <cctype> header file is required for the “is” functions
Function Description
isalnum Is the character alphanumeric? (A-Z, a-z, 0-9)
isalpha Is the character a letter? (A-Z, a-z)
iscntrlIs the character a control character? (ASCII values 0-31 and 127)
isdigit Is the character a digit? (0-9)
ispunct Is the character punctuation?
isspace Is the character whitespace? (ASCII values 9-13 and 32)
9.8.2 The “is” Functions
All of the “is” functions can be used in a similar manner as shown below
// Example 1if ( isalpha( grade ) == 0 ) { cout << "Error: Not a letter grade!";}// Example 2if ( !isalpha( grade ) ) { cout << "Error: Not a letter grade!";}
9.9 Structure Charts
Structure Chart - tool to help better visualize the organization of our solution or program
• Like a flowchart, uses symbols and connectors
• Higher level approach versus flowchart
• Graphically shows the tasks or functions needed as well as the relationship of these tasks to each other
9.9 Structure Charts
PrintOutput
main
Fun1 Fun2
Fun3PrintOutput
PrintOutput
• Allows visualizing which functions a specific function calls
• The symbol for PrintOutput was used to show that function is called from more than one function – parameters are NOT shown
9.11 C – The DifferencesUnlike C++, there is a difference between a void parameter and an empty parameter list
• void parameter list specifies there are no parameters passed to the function
• Empty parameter list specifies an indeterminate number of parameters that could be passed to a function
9.11 C – The DifferencesCan not specify default arguments in C
The functionality of passing by reference is accomplished in a much different manner called passing by pointer• Since this is covered in Chapter 12, refer to that
chapter• In C, passing by pointer is often called passing
by reference
top related