Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Functions.

Similar presentations


Presentation on theme: "Chapter 9 Functions."— Presentation transcript:

1 Chapter 9 Functions

2 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

3 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 Output Magic Happens Here

4 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

5 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

6 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

7 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

8 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 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

10 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

11 9.2 Function Components Three components to every function (including predefined functions): Declaration Definition (body) Call

12 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

13 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++

14 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> );

15 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

16 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.)

17 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

18 9.2.1 Function Declaration // Returns nothing, is passed nothing
void DisplayMenu(); void PrintInstructions( void ); // Returns an integer and is passed nothing int ReadData(); // Returns an integer and is passed two integers int FindMaximum( int value1, int value2 ); // Returns nothing, passed a float, a double and a bool void DisplayResults( float, double, bool );

19 9.2.2 Function Definition Function definition - defines what the function does Two 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

20 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 nothing void 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

21 9.2.2 Function Definition Must be placed outside of any other function
Syntactically incorrect to define a function within another function

22 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

23 9.2.3 Function Call // Function returns no value PrintInstructions();
// Function returns an integer cout << "Maximum number is: " << FindMaximum( val_1, val_2 ); int max_value = FindMaximum( val_1, val_2 ); // Returns an integer but value is never used FindMaximum( val_1, val_2 );

24 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

25 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 **"; }

26 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;

27 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

28 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;

29 9.3 return Not 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

30 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

31 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

32 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

33 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

34 9.4 Passing parameters // Declaration/Prototype
int CalculateBoxVolume( int len, int wid, int h ); int main() { int length = 3, width = 4; ... // Call int box_vol = CalculateBoxVolume( length, width, 2 ); return 0; } // Definition int CalculateBoxVolume( int len, int width, int height ) return len * width * height;

35 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

36 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

37 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

38 * Values after calculations
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 function int CalcDays( int age ) { int days; // Since Ralph lied about // his age age += 35; days= age * DAYS_IN_YEAR; return days; 20 age days 1000 1004 main Before Call CalcDays main After Call age* days* age days 55 20075 20 20075 2000 2004 1000 1004 Addresses * Values after calculations

39 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 );

40 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

41 * Values after calculations
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 function int CalcDays( int & age ) { int days; // Since Ralph lied about // his age age += 35; days= age * DAYS_IN_YEAR; return days; 20 age days 1000 1004 main Before Call CalcDays main After Call age* days* age days 20075 55 20075 Addresses 2000 2004 1000 1004 * Values after calculations

42 9.4.4 Passing by Reference Following example passes parameters both by value and by reference // Two parameters passed by reference void Swap( int & a, int & b ); // Two parameters passed by value, one by reference void FindAverage( double a, double b, double &average ); int EnterData( int &id, char &code );

43 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

44 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

45 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

46 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

47 9.5 Default Arguments Put default values only in the function declaration or prototype - do NOT include them in the function header

48 9.5 Default Arguments // Function declarations ONLY
void 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 options DisplayMenu( times ); DisplayMenu(); DisplayMenu( 3 ); PrintInstructins( 5, 10 ); PrintInstructions( 7 ); ReadData( records ); ReadData( records, 50.5 ); ReadData( records, 50.2, 11 );

49 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 ); return 0; } void PrintOutput( int a, int b ) 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 ); Fun3( a, b ); void Fun3( int & c, int & d ) c = 25; d = 10; PrintOutput( c, d );

50 9.6 Putting It All Together
// Output

51 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

52 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)

53 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

54 9.8 More Predefined Functions
Chapter 6 discussed some of the predefined mathematical functions The following functions manipulate individual characters

55 9.8.1 Character Case To 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

56 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 call while ( toupper( again ) == 'Y' ) { cout << "\n wish to multiply two more numbers (y/n)? "; }

57 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

58 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 );

59 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) iscntrl Is 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)

60 9.8.2 The “is” Functions All of the “is” functions can be used in a similar manner as shown below // Example 1 if ( isalpha( grade ) == 0 ) { cout << "Error: Not a letter grade!"; } // Example 2 if ( !isalpha( grade ) )

61 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

62 9.9 Structure Charts PrintOutput main Fun1 Fun2 Fun3 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

63 9.11 C – The Differences Unlike 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

64 9.11 C – The Differences Can 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


Download ppt "Chapter 9 Functions."

Similar presentations


Ads by Google