Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Functions §5.1 Basics of Function §5.2 Parameter Passing §5.3 Function Overloading §5.4 Prototype and Reuse §5.5 The Scope of Variables §5.6.

Similar presentations


Presentation on theme: "Chapter 5 Functions §5.1 Basics of Function §5.2 Parameter Passing §5.3 Function Overloading §5.4 Prototype and Reuse §5.5 The Scope of Variables §5.6."— Presentation transcript:

1 Chapter 5 Functions §5.1 Basics of Function §5.2 Parameter Passing §5.3 Function Overloading §5.4 Prototype and Reuse §5.5 The Scope of Variables §5.6 Function Abstraction §5.7 Inline Functions

2 §5.1 Basics of Function Definition of Function – A collection of statements that are grouped together to perform an operation. Benefits of Function – Problem simplifying “Divide and conquer” – Code reusing Avoid re-coding, re-compiling – Information hiding Hide the implementation from the user A special function – main() 2 Caller function Calling “F” Callee ”F”

3 Creating a Function 3 int max(int x, int y) { int z; if (x >= y) z = x; else z = y; return z; } Return value type Function name Function header List of parameters (formal parameters) Function body Return value returnValueType functionName (list of parameters) { //Function body Statements; }

4 Function header – Return value type + function name + parameter list Function signature ( 签名 ) – Function name + parameter list Formal parameter ( 形式参数 ) – The variables defined in the function header – Parameters are optional Return Value Type ( 返回值类型 ) – The data type of the value the function returns – Void function: no return value and return value type is “void” – Default type (returnValueType is omitted): int not supported anymore VS! Function Header 4 return expresion1;

5 The collection of statements defining what the function does “return” statement is required for value-returning functions A function terminates when a return statement is executed – Although there may be some statements left Function Body ( 函数体 ) 5 int max(int x, int y){ int z; return z; if (x >= y) z = x; else z = y; }

6 To use a function: call/invoke it Calling a Function 6 Caller function ( 主调函数) Calling “F” Callee ”F” (被调函数) Make sure a function has been created/declared before calling it!!!

7 Trace of Function Invocation 7 i is now 5j is now 2 invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 (num1 > num2): true 5>2 result is now 5 return result, 5 invoke max(i, j) return max(i, j) and assign the return value to k Execute the print statement

8 Call Stacks ( 调用栈 ) 8

9 9 Trace Call Stack i is declared and initialized

10 10 Trace Call Stack j is declared and initialized

11 11 Trace Call Stack Declare k

12 12 Trace Call Stack Invoke max(i, j)

13 13 Trace Call Stack pass the values of i and j to num1 and num2

14 14 Trace Call Stack (num1 > num2) is true

15 15 Trace Call Stack Assign num1 to result

16 16 Trace Call Stack Return result and assign it to k

17 17 Trace Call Stack Execute print statement

18 Write functions headers to – Test whether a number is even – Convert a lowercase letter to an uppercase one Identify errors in the functions Review Questions 18 int myFunc(int n){ cout<<n<<endl; } void yourFunc(int a, b){ cout<<a+b<<endl; } hisFunc(int n){ return n*n; } int max(int x, int y){ int z; if (x >= y) z = x; else z = y; return z; }

19 Actual Parameter ( 实际参数 ) – When a function is invoked, you pass a value to the parameter. – This value is referred to as actual parameter or argument. The list of arguments in an invocation must be consistent with the list of formal parameters – Number, sequence, and type §5.2 Parameter Passing ( 参数传递 ) 19

20 Parameter Passing Methods Two methods of passing parameters – Pass-by-value ( 按值传递 / 调用 ) – Pass-by-reference ( 按引用传递 / 调用 ) 20

21 Pass-by-Value The “value” of an argument is passed to the parameter “directly”. 21

22 Pass-by-Value The value of an argument variable is NOT affected by the change made to the parameters inside the function 22 TestPassByValue

23 Reference variable – a special type of variable – an alias for another variable – Syntax: & = Pass-by-Reference 23 int count = 1; int &refCount = count; 1 count refCount

24 Listing 5.5: a program declares a reference of an integer variable Example of Reference Variables 24 TestReferenceVariable

25 The “reference” of an argument is passed to the parameter. How to do? – In function declaration: use reference variables as formal parameters – In function invocation: use regular variables as arguments Pass-by-Reference 25 Int max(int &x, int &y){ int z; if(x>=y) z=x; else z=y; return z; } int main(){ int a=3, b=5; cout<<max(a,b)<<endl; }

26 The value of an argument variable is affected by the change made to the parameters inside the function Listing 5.6. a program that swaps the values of two variables. Example of Pass-by-Reference 26 TestPassByReference

27 Parameters declared with default values Default Arguments ( 缺省参数 ) 27 DefaultArgumentDemo type name(type para1, …, type parai=defaultvalue, …) { //Function body Statements; } Note: Default arguments must be declared at last int max(int x, int y=0, int z=0){ … } int max(int x, int y=0, int z){ … }

28 Show the output of the following programs Review Questions 28 void maxVal(int val1, int val2, int max){ if(val1>val2) max = val1 else max = val2; } int main(){ int n1 = 19, n2 = 28, max = 0; maxVal(n1, n2, max); cout<<"Max is "<<max; } void f(double &p){ p+=2; } int main(){ double x = 10; int y = 10; f(x); f(y); cout<<x<<", "<<y; }

29 Overloading ( 重载 ): two functions within one file with – The same name, but – Different parameter lists The types and/or the number of arguments §5.3 Function Overloading 29 int max(int x, int y){ … } float max(float x, float y){ … } int max(int x, int y, int z){ … } Different parameter type Different parameter number Return value type does not matter!!!

30 Listing 5.7. overloading the “max()” functions. Example of Function Overloading 30 TestFunctionOverloading

31 Implicit type conversion may be done in function invocation Type Conversion and Overloading 31 float max(float x, float y){ float z; if(x>=y) z=x; else z=y; return z; } int main(){ int a=3, b=5; cout<<max(a,b)<<endl; } long double double float unsigned long long unsigned int int

32 Function version determination Which version of a overloaded function should be called for an invocation? – First: the one with exactly matching parameter list – Second: the one matching after type conversion Ambiguous invocation – No exactly matching version – More than one matching after conversion Will cause a compilation error! Ambiguous Invocation 32

33 Example of Ambiguous Invocation 33 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; }

34 Are the following programs correct? Review Questions 34 void p(int i) { cout<< i <<endl; } int p(int x) { cout<< x +1 <<endl; } void p(int &t) { cout<<t*t<<endl; }

35 Function prototype ( 原型 ) – A function declaration without implementation (the function body). – The implementation can be given later in the program, after the calling of the function Function prototypes are usually put in the beginning of a program – To make sure the callings occur after declaration §5.4 Prototype and Reuse 35 type name(type para1, type2 para2, …); type name(type1, type2, …);

36 Listing 5.8. a revision of the program that compute the maximum value. Example of Function Prototype 36 TestFunctionPrototype

37 Listing 5.10. Revision of Listing 3.5 by using functions. Case Study: Computing Taxes 37 if (status == 0) { // Compute tax for single filers }else if (status == 1){ // Compute tax for married file jointly }else if (status == 2) { // Compute tax for married file separately }else if (status == 3) { // Compute tax for head of household }else { // Display wrong status }

38 Define a function to compute tax for each filing status. Case Study: Computing Taxes 38 ComputeTaxWithFunction computeTax(400000, 6000, 27950, 67700, 141250, 307050)

39 To make the functions available for other programs to use – One of the benefits of functions How to do? – Place the functions in a separate file, called header file. By convention, the file has a “.h ” or “.hpp ” extension. – Programs use #include preprocessor directives to include header files Reusing Functions 39 MyLib.hUseMyLib.cpp

40 Random character  random ASCII code  random number 0~127  random() Case Study: Generating Random Characters 40 RandomCharacter.h TestRandomCharacter

41 Any variable is “ accessible ” within some specific part of a program Scope ( 作用域 ) – The part of the program where the variable can be referenced. Local variable vs. global variable ( 局部变量 ) ( 全局变量 ) §5.5 The Scope of Variables 41

42 Local variable – A variable defined inside a function. The scope of a local variable – From its declaration and continues to the end of the block that contains the variable. Local Variables 42 Initialize a local variable before using it!

43 A block can be: Scope of Local Variables 43 A function A flow control block A common statement block int max(int x, int y){ … int i=0; … } for (int i=0; i<10;i++){ … int j=0; … } … { … int j=0; … } …

44 Scope of Local Variables 44 not good to In this scope, the outer “i” is shielded by the inner one.

45 Global variable – Declared outside any function – With global scope Accessible to all functions A global variable is automatically initialized by the system to zero Global Variables 45 int globalvaue; Int main(){ } int globalvaue = 0; Int main(){ }  VariableScopeDemo

46 “ :: ” : used to access the global variable if it has the same name as a local variable ::globalVariable Unary Scope Resolution 46 int v1 = 10; int main(){ int v1 = 5; cout << "local variable v1 is " << v1 << endl; cout << "global variable v1 is " << ::v1 << endl; return 0; }

47 Lifetime: – The period of time during which it is available for use. Global lifetime: – Global variables’ lifetime – The lifetime of the entire program Temporary lifetime: – Local variables’ lifetime – Part of the lifetime of the entire program The execution time of the variable’s code block (its scope) Lifetime of Variables 47

48 static (= ); Global lifetime – Permanently allocated in the memory for the lifetime of the program Local Scope – The same scope as a non-static variable Initialization – Only once!!! – By the system( to zero) or by user Static Local Variables 48

49 Listing 5.16. a program shows the use of static local variable. The static variable declared in a function retains the value between two calls. Example of Static Local Variable 49 StaticVariableDemo

50 Identify the variable types in the following program Review Questions 50 int x = 0; void show(int k) { static int j=0; j++; cout<<k<<endl<<j<<endl; } int main() { int i; for(i=0; i<3; i++){ cin>>x; show(x); }

51 §5.6 Function Abstraction You can think of the Function body as a black box that contains the detailed implementation for the function. 51 Function designFunction abstraction

52 Also known as “divide and conquer” – The strategy used to design functions – Decompose the problem into subproblems. – The subproblems can be further decomposed into smaller, more manageable problems. Two steps of function design – Design – Implementation Two methods – Top-down – Bottom-up Stepwise Refinement 52

53 Listing 5.17. A program that displays the calendar of a given month of the year. The program prompts the user to enter the month and year, and then displays the results. Case Study: Print Calendar 53 PrintCalendar

54 Design: Top-down 54

55 To implement the high level (parent) functions first and then the low level (child) functions. – For each Function implemented, write a test program to test it. Stubs can be used for the low level functions waiting to be implemented. – A stub is a simple but incomplete version of a Function. – The use of stubs enables you to test invoking the function from a caller. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this: Implementation: Top-Down 55 A Skeleton for printCalendar

56 To implement the low level (child) functions first and then the high level (parent) functions. Both top-down and bottom-up are fine. – Both approaches implement the Functions incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together. Implementation: Bottom-Up 56

57 Cost of functions – Runtime overhead caused by function calls Pushing arguments and CPU registers into the stack Transferring control to and from a function Inline function ( 内联函数 ) – A function not called by the caller. – The compiler copies the function code in line at the point of each invocation. §5.7 Inline Functions 57

58 inline (para list) Example: Listing 5.18. the use of inline function to print information. It is essentially equivalent to Listing 5.19. Declaration of Inline Functions 58 InlineDemo InlineDemo1

59 Used for short functions rather than long functions – Copying long function codes lengthens the program A long “ inline ” function may be treated as a common function: the “ inline ” is ignored. – The compiler makes such decisions Notes for Inline Functions 59

60 The declaration and use of functions Reference variable Pass-by-value vs. Pass-by-reference Overloading functions – Different in parameter list Prototype and modular programming Local variable vs. Global variable – Scope and lifetime Function design – Top-down vs. Bottom up Inline function Summary 60

61 Q1. True or false? – A function prototype must specify the function name and the name of each parameter. – If a function has six parameters, six arguments must be put in the call statement. – Parameters are used for only pass data from caller to callee. Q2. Please briefly describe the advantage of using functions. Homework Questions 61

62 Q3. Show the output of the following programs Homework Questions 62 int num =0; void func1(){ static int num_1=0; num_1++; num++; cout <<num_1<<"\t"<<num<<endl; } void func2(){ static int num_2=0; num_2++; num++; cout <<num_2<<"\t"<<num<<endl; } int main(){ for(int i=0; i<3; i++) if(i%2) func1(); else func2(); return 0; }

63 Q4. The following program try to count the number of vowels in the characters read from keyboard. Can it work correctly? Point out the errors if any. Homework Questions 63 int checkVowels(char ch){ if(ch== 'a' || 'e' || 'i' || 'o' || 'u' ) novowels++; } int main(){ int novowels; char ch; cout<<"Enter letters, '0' to exit\n"; cin>>ch; for(;ch!='0';){ if(97<=ch<=122||65<=ch<=90) checkVowels(ch); else break; cin>>ch; } cout<<“# of vowels:"<<novowels<<endl; }


Download ppt "Chapter 5 Functions §5.1 Basics of Function §5.2 Parameter Passing §5.3 Function Overloading §5.4 Prototype and Reuse §5.5 The Scope of Variables §5.6."

Similar presentations


Ads by Google