1 / 41

Chapter 5 Function Basics

Chapter 5 Function Basics. Motivations.

bree
Download Presentation

Chapter 5 Function Basics

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 5 Function Basics

  2. Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a program and reuse it by many other programs. For example, often you need to find the maximum between two numbers. Whenever you need this function, you would have to write the following code: If you define this function for finding a maximum number between any two numbers in a method, you don’t have to repeatedly write the same code. You need to define it just once and reuse it by any other programs. int result; if (num1 > num2) result = num1; else result = num2;

  3. Motivations • Functions allow one to reuse code • But functions also reduce conceptual complexity: • Alternator • Brown sauce

  4. Objectives • To define functions (§5.2). • To invoke functions with a return value (§5.3). • To invoke functions without a return value (§5.4). • To pass arguments (§5.5). • To develop reusable code that is modular, easy-to-read, easy-to-debug, and easy-to-maintain (§5.6). • To use function overloading and understand ambiguous overloading (§5.7). • To use function prototypes for function headers (§5.8). • To create header files for reusing functions (§5.9). • To separate function headers from implementation (§5.10). • To develop functions for generating random characters (§5.11). • To develop applications using the C++ mathematical functions (§5.12). • To develop applications using the C++ character functions (§5.13).

  5. Introducing Functions A function is a collection of statements that are grouped together to perform an operation.

  6. Introducing Functions, cont. • Function signature is the combination of the function name and the parameter list. • The variables defined in the function header are known as formal parameters. • When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

  7. Introducing Functions, cont. • A Function may return a value. The returnValueType is the data type of the value the function returns. If the function does not return a value, the returnValueType is the keyword void. • Void function vs. procedure vs. subroutine

  8. Calling Functions Listing 5.1 Testing the max Function This program demonstrates calling a Function max to return the largest of the int values TestMax

  9. animation Calling Functions, cont.

  10. animation Trace Function Invocation i is now 5

  11. animation Trace Function Invocation j is now 2

  12. animation Trace Function Invocation invoke max(i, j)

  13. animation Trace Function Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

  14. animation Trace Function Invocation declare variable result

  15. animation Trace Function Invocation (num1 > num2) is true since num1 is 5 and num2 is 2

  16. animation Trace Function Invocation result is now 5

  17. animation Trace Function Invocation return result, which is 5

  18. animation Trace Function Invocation return max(i, j) and assign the return value to k

  19. animation Trace Function Invocation Execute the print statement

  20. Call Stacks

  21. animation Trace Call Stack i is declared and initialized

  22. animation Trace Call Stack j is declared and initialized

  23. animation Trace Call Stack Declare k

  24. animation Trace Call Stack Invoke max(i, j)

  25. animation Trace Call Stack pass the values of i and j to num1 and num2

  26. animation Trace Call Stack (num1 > num2) is true

  27. animation Trace Call Stack Assign num1 to result

  28. animation Trace Call Stack Return result and assign it to k

  29. animation Trace Call Stack Execute print statement

  30. void Functions The preceding section gives an example of a nonvoid function. This section shows how to declare and invoke a void function. Listing 5.2 gives a program that declares a function named printGrade and invokes it to print the grade for a given score. TestVoidFunction TestReturnGradeFunction

  31. Modularizing Code Methods can be used to reduce redundant coding and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. GreatestCommonDivisorFunction PrimeNumberFunction

  32. Overloading Functions The max function that was used earlier works only with the int data type. But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another function with the same name but different parameters, as shown in the following code: TestFunctionOverloading

  33. Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a function, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

  34. Ambiguous Invocation #include <iostream> using namespace std; int maxNumber(int num1, double num2) { if (num1 > num2) return num1; else return num2; } double maxNumber(double num1, int num2) { if (num1 > num2) return num1; else return num2; } int main() { cout << maxNumber(1, 2) << endl; return 0; }

  35. Function Prototypes Before a function is called, it must be declared first. One way to ensure it is to place the declaration before all function calls. Another way to approach it is to declare a function prototype before the function is called. A function prototype is a function declaration without implementation. The implementation can be given later in the program. TestFunctionPrototype

  36. Reusing Functions by Different Programs One of the benefits of functions is for reuse. In the preceding sections, you declared functions and used them from the same program. To make the functions available for other programs to use, you need to place the functions in a separate file, called header file. By convention, the file has a .h extension. Programs use #include preprocessor directives to include header files in order to reuse the functions defined in the header file. MyLib.h UseMyLib.cpp

  37. Case Study: Generating Random Characters Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. As introduced in §2.11, every character has a unique ASCII code between 0 and 127. To generate a random character is to generate a random integer between 0 and 127. You learned how to generate a random number in §3.8. Recall that you can use the srand(seed) function to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example,

  38. Case Study: Generating Random Characters, cont. RandomCharacter.h TestRandomCharacter

  39. Math Functions Math Functions Run

  40. Character Functions

  41. Case Conversion Functions CharacterFunctions Run

More Related