C++ FOR ENGINEERS AND SCIENTISTS THIRD EDITION Chapter 6 Modularity Using Functions
Objectives 2 In this chapter, you will learn about: Function and parameter declarations 函數和參數宣告 Returning a single value 回傳單一值 Returning multiple values 回傳多值 Rectangular to polar coordinate conversion 直角座標到極座標轉換 Variable scope 變數有效範圍 Variable storage categories 變數儲存種類 Common programming errors 常見錯誤
3 6.1 function and parameter declarations 函數和參數宣告
Function and Parameter Declarations 函 數和參數宣告 4 Interaction with a function includes: 使用函數包括 Passing data to a function correctly when its called 正確地傳資料給函數 Returning values from a function when it ceases operation 函數終止時接收回傳資料 A function is called by giving the function s name and passing arguments in the parentheses following the function name 呼叫函數的方法 : 函數名稱 ( 參數 1 參數 2 ) Figure 6.1 Calling and passing data to a function 呼叫和傳資料給函數
Function and Parameter Declarations (continued) 5 在此宣告函數 找最大值 函數原型後面會有說明 在此呼叫函數
Function and Parameter Declarations 6 (continued) Before a function is called, it must be declared to function that will do calling 函數被呼叫之前要先宣告 Declaration statement for a function is referred to as function prototype 這個宣告稱為函數原型 Function prototype tells calling function: 函數原型告訴呼叫函數 : Type of value that will be formally returned, if any 回傳資料型態 Data type and order of the values the calling function should transmit to the called function 所需提供資料種類和順序 Function prototypes can be placed with the variable declaration statements above the calling function name or in a separate header file 函數原型可以放在變數宣告處 ( 在呼叫函數之前 ) 或另一個標頭檔案中
Calling a Function 呼叫函數 7 Requirements when calling a function include: 呼叫一個函數需要 Using the name of the function 函數名稱 Enclosing any data passed to the function in the parentheses following the function name, using the same order and type declared in the function prototype 所需資料或參數放在括號中, 順序和種類必須與函數原型相同
Calling a Function (continued) 8 The items enclosed in the parentheses are called arguments of the called function 括號中的參數稱為引數 Figure 6.2 Calling and passing two values to findmax() 呼叫並傳送兩個資料給 findmax()
Calling a Function (continued) 9 只有參數值被複製一份傳送到函數原始值不受影響 Figure 6.3 The findmax() function receives actual values
Calling a Function (continued) 10 Figure 6.3: The findmax() function does not receive the variables named firstnum and secnum and has no knowledge of the variable names 被呼叫函數不知道原始變數名稱的存在 The function receives the values in these variables and must then determine where to store those values before it does anything else 被呼叫函數只是接受數值而且決定該把這些數值放在哪裡
Defining a Function 定義函數 11 Every C++ function consists of two parts: 每個 C++ 函數都有兩個部分 Function header 函數標頭 Function body 函數主體 Function header s purpose: 函數標頭的目的 Identify data type of value function returns, provide function with name, and specify number, order, and type of arguments function expects 指定函數回傳的資料型態 提供函數名稱 指定引數的數目 順序和型態 Function body s purpose: 函數主體的目的 To operate on passed data and return, at most, one value directly back to the calling function 將傳來的資料加以運算, 而且回傳至多一個結果數值
Defining a Function (continued) 12 Figure 6.4 The general format of a function 原始的變數名稱 Figure 6.5 Storing values in parameters 函數自己為接收的數值取名字
Program 6.2 13
Placement of Statements 敘述的放 14 置順序 General rule for placing statements in a C++ program: 一般規則 All preprocessor directives, named constants, variables, and functions must be declared or defined before they can be used 預處理指令 常數 變數和函數可以在任何地方宣告 ( 只要在使用前 ) Although this rule permits placing both preprocessor directives and declaration statements throughout the program, doing so results in poor program structure 但是這是不佳的程式習慣
Functions with Empty Parameter 15 Lists 沒有引數的函數 Although useful functions having an empty parameter list are extremely limited, they can occur 函數可以沒有引數 Function prototype for such a function requires writing the keyword void or nothing at all between the parenthesis following the function s name 括號中寫 void 或空白
Default Arguments 預設引數 16 C++ provides default arguments in a function call for added flexibility 在 C++ 函數呼叫中可以有預設引數 Primary use of default arguments is to extend parameter list of existing functions without requiring any change in calling parameter lists already used in a program 用來延伸引數清單而不必修改程式 Default arguments are listed in the function prototype and transmitted automatically to the called function when the corresponding arguments are omitted from the function call 當對應的引數省略時, 函數原型中所設定的預設值會自動傳給函數
Default Arguments (continued) 17 Example: Function prototype with default arguments 函數原型加上預設引數 void example(int, int = 5, double = 6.78) Sample valid calls to the example function example(7,2,9.3) // no defaults used example(7,2) // same as example(7, 2, 6.78) example(7) // same as example(7, 5, 6.78) 若要省略參數從最右方開始省略, 不可以只省略中間
Reusing Function Names (Overloading) 函數超載 18 C++ provides the capability of using the same function name for more than one function 使用相同的函數名稱 Referred to as function overloading 函數超載 Only requirement for creating more than one function with same name: 唯一要求 Compiler must be able determine which function to use based on the parameters data types (not the data type of the return value, if any) 編譯器必須能根據引數資料型態 ( 必須不同 ) 決定呼叫的函數, 而不是根據回傳資料型態
Reusing Function Names (Overloading) (continued) 19 Which of the functions is called depends on the argument type supplied at the time of the call 依照呼叫時提供的資料型態決定哪一個函數被呼叫 兩個函數名稱相同, 只有引數資料型態不同
Function Templates 函數模板 20 Function template: Single complete function that serves as a model for a family of functions 單一函數作為一群函數的模型 Function from the family that is actually created depends on the specific function call 視特定的呼叫產生特定的函數 Generalize the writing of functions that perform essentially the same operation, but on different parameter data types 便於撰寫使用不同的引數資料種類以處理相同工作的一群函數 Make it possible to write a general function that handles all cases but where the compiler can set parameters, variables, and even return type based on the actual function call 用來編寫處理各類資料的通用函數, 由編譯器依需求選擇資料種類
Program 6.3 21
Program 6.4 22
23 6.2 returning a single value 只回傳單一值的函數
Returning a Single Value 回傳單一值 24 Function receiving an argument passed by value cannot inadvertently alter value stored in the variable used for the argument 不會不小心變更原始變數資料 Function receiving passed by value arguments can process the values sent to it in any fashion and return one, and only one, legitimate value directly to the calling function 函數可以處理傳來的資料但最多只能回傳一個值 Figure 6.6 A function directly returns at most one value
Returning a Single Value (continued) 25 findmax function 前後資料型態要相同
Inline Functions 行中函數 26 Calling a function places a certain amount of overhead on a computer 呼叫函數對電腦造成負擔 Placing argument values in a reserved memory region (called the stack) that the function has access to 把引數放在堆疊區 Passing control to the function 把控制傳給函數 Providing a reserved memory location for any returned value (again, using the stack for this purpose) 將回傳值放在堆疊區中 Returning to the correct point in the calling program 將控制交回呼叫者
Inline Functions (continued) 27 Paying overhead associated with calling a function is justified when a function is called many times 如果呼叫該函數很多次是值得的 Can reduce a program s size substantially 可以減少程式的大小 For small functions that are not called many times, overhead of passing and returning values might not be warranted 對於呼叫次數少的小程式則不值得 Inline functions: Group repeating lines of code together under a common function name 將重複的幾行程式放在一起 Have the compiler place this code in the program wherever the function is called 讓編譯器將程式碼插入
Program 6.5 findmax 函數 28
Program 6.6 非 inline 的溫度轉換 29
改用 inline 做溫度轉換 30
Inline Functions (continued) 31 Advantage: Increase in execution speed 行中函數加快執行速度 Because the inline function is expanded and included in every expression or statement calling it, no execution time is lost because of the call and return overhead a non-inline function requires 因為是插入程式碼, 所以沒有執行時的額外負擔 Each time an inline function is referenced the complete code is reproduced and stored as an integral part of the program 每次呼叫時, 行中函數便會複製一次存入程式中 A non-inline function is stored in memory only once 一般函數只儲存一次 Inline functions should be used only for small functions that aren t called extensively in a program 只應用於不常用的小函數
32 6.3 returning multiple values 回傳多值的函數
Returning Multiple Values 傳回多值 33 In typical function invocation, called function receives values from its calling function stores and manipulates the passed values, and directly returns at most one value 到目前為止函數可以接收好幾個值, 但只傳回一個值 Pass by value: When data is passed in this manner 這叫做傳值 Pass by reference: Giving a called function direct access to its calling function s variables is referred to as 另一種是傳記憶體地址 The called function can reference, or access, the variable whose address has been passed as a pass by reference argument 被呼叫函數可以直接存取傳送的變數
Passing and Using Reference 34 Parameters 傳送和使用參考參數 From the sending side, calling a function and passing an address as an argument that s accepted as a reference parameter is the same as calling a function and passing a value 對呼叫函數的一方來說, 傳值和傳地址是相同的工作 Whether a value or an address is actually passed depends on the parameter types declared 傳值或傳地址是依照引數型態而決定
Passing and Using Reference 35 Parameters (continued) 主程式中看待參數的名稱 傳記憶體位址 函數中看待參數的名稱 Figure 6.7 The equivalence of arguments and parameters in Program 6.8
Program 6.8 - explain 36
Passing and Using Reference Parameters (continued) 37
Program 6.10 38
Passing and Using Reference 39 Parameters (continued) 傳值 參數複製存取不同的版本 傳地址 存取同一個參數 Figure 6.8 The relationship between argument and parameter names
Passing and Using Reference Parameters (continued) 40 Figure 6.9a Save the first value 兩個數字互換的方式需要有第三個臨時參數 Figure 6.9b Replace the first value with the second value Figure 6.9c Change the second value
41 6.4 a case study 案例分析
42 A Case Study: Rectangular to Polar Coordinate Conversion 直角座標轉極座標 Figure 6.10 The problem-solver algorithm
A Case Study: Rectangular to Polar 43 Coordinate Conversion (continued) Figure 6.11 The correspondence between polar (distance and angle) and Cartesian (x and y) coordinates
A Case Study: Rectangular to Polar 44 Coordinate Conversion (continued) Figure 6.12 A top level structure diagram
A Case Study: Rectangular to Polar 45 Coordinate Conversion (continued) Figure 6.13 Parameter values when polar() is called
Program 6.11 程式分解 : 轉換座標的函數 46
Program 6.12 程式分解 : 取得輸入座標的函數 47
程式分解 : 顯示結果的函數 48
Program 6.14 合併三個函數 49
50 6.5 variable scope 變數的有效範圍
Variable Scope 參數有效範圍 51 A function can be thought of as a closed box, with slots at the top to receive values and a single slot at the bottom to return a value 把函數想成一個盒子, 上面的孔接受數值, 下面的孔輸出結果 Figure 6.14 A function can be considered a closed box
Variable Scope (continued) 52 Local variables: Variables created in a function that are conventionally available only to the function 區域變數 : 在函數中宣告, 只在函數中有效 Scope: Section of the program where the identifier is valid or known 有效範圍 : 識別字可以被辨識的範圍 A variable with local scope is simply one with storage locations set aside for it by a declaration statement inside the function that declared them 局部有效範圍 : 由函數中的宣告敘述保留空間 A variable with global scope has storage created for it by a declaration statement located outside any function 全域有效範圍 : 由不在任何函數內的宣告敘述保留空間
Variable Scope (continued) 53 Figure 6.15 The three storage areas reserved by Program 6.15
Variable Scope (continued) 54 Figure 6.16 Relating the scope and type of a variable
Program 6.15 55 想想結果會是什麼?
Scope Resolution Operator 56 When a local variable has the same name as a global variable, all references to the variable name made within the local variable s scope refer to the local variable 如果變數名稱相同先用區域變數
Scope Resolution Operator 57 (continued) To reference a global variable when a local variable of the same name is in scope, use C++ s scope resolution operator, which is :: 強制使用全域變數的符號
Misuse of Globals 全域變數的誤用 58 Global variables allow programmers to jump around the normal safeguards provided by functions 全域變數使得程式設計師避開函數的保護 Instead of passing variables to a function, it is possible to make all variables global: do not do this 不要把所有變數改為全域變數 Indiscriminate use of global variables destroys the safeguards C++ provides to make functions independent and insulated from each other 全域變數的濫用會破壞函數的安全屏障 Using only global variables can be especially disastrous in large programs with many user-created functions
Variable Storage Categories 59 A variable s scope can be thought of as the space in the program where the variable is valid 變數有效範圍可以想成變數可用的空間 In addition to space dimension represented by scope, variables have a time dimension that refers to the length of time storage locations are reserved for a variable 空間向度和時間向度 This time, dimension is referred to as the variable s lifetime 變數的生命期 When and how long a variable s storage locations are kept before they are released can be determined by the variable s storage category 儲存類別說明何時和多久一個變數儲存區域可以被保留
Variable Storage Categories 60 (continued) The four available storage categories are: 四種儲存種類 auto static extern register
Local Variable Storage Categories 61 Local variables can be members only of the auto, static, or register storage categories 局部變數僅可以是 auto, static, or register auto is short for automatic Storage for automatic local variables is reserved or created automatically each time a function As long as the function hasn t returned control to its calling function, all automatic variables local to the function are alive 只要函數還未交回控制權, 所有 auto 局部變數都會有效 A local static variable isn t created and destroyed each time the function declaring it is called Local static variables remain in existence for the program s lifetime 局部 static 變數在整個程式中都有效
Local Variable Storage Categories (continued) 62
Local Variable Storage Categories (continued) 63
Local Variable Storage Categories 64 (continued) Most computers have a few high-speed storage areas, called registers, located in the CPU that can also be used for variable storage 大多數電腦有一個高速儲存區域稱為 registers Because registers are located in the CPU, they can be accessed faster than normal memory storage areas located in the computer s memory unit 因為 registers 在 CPU 中, 所以它們比正常記憶體快
Global Variable Storage 65 Categories Global variables are created by definition statements external to a function 全域變數由所有函數外的宣告產生 By their nature, global variables do not come and go with the calling of a function 全域變數不會因呼叫函數而消失 After a global variable is created, it exists until the program in which it s declared has finished executing Global variables can be declared with the static or extern storage category, but not both 全域變數可以宣告為 static or extern, 但不能兩者同時
Global Variable Storage Categories (continued) 66 Figure 6.17 A program can extend beyond one file 一個程式可以超出一個檔案
Global Variable Storage Categories (continued) 67 Figure 6.18 Extending the scope of global variables 延伸全域變數的範圍
Common Programming Errors 68 Passing incorrect data types 傳送錯誤資料型態 Errors that occur when the same variable is declared locally in both the calling and the called functions 同樣變數宣告兩次 Omitting the called function s prototype before or within the calling function 忘記函數原型 Terminating a function header with a semicolon 函數標題用分號結尾 Forgetting to include the data type of a function s parameters in the function header 忘記在函數標頭中加入資料型態
Chapter Summary 69 A function is called by giving its name and passing any data to it in the parentheses following the name A function s return type is the data type of the value the function returns Arguments passed to a function when it is called must conform to the parameters specified by the function header in terms of order, number of arguments, and specified data type
Chapter Summary (continued) 70 Functions can be declared to all calling functions by means of a function prototype Every variable has a storage category, which determines how long the value in the variable is retained