1 / 64

Chapter 9 Functions

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

Download Presentation

Chapter 9 Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9Functions

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

  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 declarationoften 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(); // Returns nothing, is passed nothing void PrintInstructions( void); // Returns an integer and is passed nothing intReadData(); // 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 components1. 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 ); // Function returns an integer intmax_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( booldone ) { cout << "Staple all pages of your application.\n"; cout << "In addition date and sign your form!\n\n"; if ( done ) returntrue; else returnfalse; // 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 boolDetermineHonorRollStatus() { doublegpa = 2.4; if( gpa > 3.50 ) { cout <<"Excellent Work" << endl; returntrue; } elseif ( gpa >= 3.0 ) { // Will produce compiler warning: Not all control paths // return a value cout << "Nice job" << endl; } else { cout << "Keep Trying" << endl;returnfalse; } }

  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 intSumTheValues() { intsum = 0, value = 0; for ( inti = 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 doublebase = 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, inth ); int main() { intlength = 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. main Before Call age days 20 0 1000 1004 9.4.3 Passing by Value 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. main Before Call age days 20 0 1000 1004 9.4.4 Passing by Reference 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(doublea,double b, double &average ); // Two parameters passed by reference 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( inttimes = 1 ); void PrintInstructions( int length, intheight = 7 ); int ReadData(int &records, double units = 45.5, intsize = 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

  50. 9.6 Putting It All Together • // Output • 2 10 • 3 9 12 • 12 10 • 17 289 • 25 10 • 25 10 • 25 10

More Related