高級(jí)語(yǔ)言程序設(shè)計(jì) chapter7_第1頁(yè)
高級(jí)語(yǔ)言程序設(shè)計(jì) chapter7_第2頁(yè)
高級(jí)語(yǔ)言程序設(shè)計(jì) chapter7_第3頁(yè)
高級(jí)語(yǔ)言程序設(shè)計(jì) chapter7_第4頁(yè)
高級(jí)語(yǔ)言程序設(shè)計(jì) chapter7_第5頁(yè)
已閱讀5頁(yè),還剩55頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、A First Book of ANSI CFourth EditionChapter 7Modularity Using Functions: Part IIA First Book of ANSI C, Fourth Edition2Objectives Variable Scope Variable Storage Class Pass by Reference Case Study: Swapping Values Recursion Common Programming and Compiler ErrorsA First Book of ANSI C, Fourth Edition

2、3Variable Scope If variables created inside a function are available only to the function itself, they are said to be local to the function, or local variables Scope is the section of the program where the variable is valid or “known”A First Book of ANSI C, Fourth Edition4Variable Scope (continued)A

3、 First Book of ANSI C, Fourth Edition5Variable Scope (continued) A variable with a local scope has had storage set aside for it by a declaration statement made within a function body A variable with global scope is one whose storage has been created for it by a declaration statement located outside

4、any functionA First Book of ANSI C, Fourth Edition6Variable Scope (continued)A First Book of ANSI C, Fourth Edition7Variable Scope (continued)A First Book of ANSI C, Fourth Edition8Variable Scope (continued) Program 7.1 produces the following outputFrom main(): firstnum = 10From main(): secnum = 20F

5、rom valfun(): firstnum = 10From valfun(): secnum = 30From main() again: firstnum = 40From main() again: secnum = 20 While a function is executing, only the storage area for the variables and parameters created by this function are automatically accessedA First Book of ANSI C, Fourth Edition9Variable

6、 Scope (continued) If a variable that is not local to the function is used by the function, the program searches the global storage areas for the correct name The scope of a variable does not influence the data type of the variableA First Book of ANSI C, Fourth Edition10Variable Scope (continued)A F

7、irst Book of ANSI C, Fourth Edition11When to Use Global Declarations The scoping rules for symbolic constants and function prototypes are the same as for variables When a symbolic constant has a general meaning that is applicable throughout an application, it makes good programming sense to declare

8、it globally at the top of a source code file Coding a function prototype as a global makes sense when the function is used by a number of other functions in a source code file Doing so avoids repeating the prototype within each of the functions that will call itA First Book of ANSI C, Fourth Edition

9、12Misuse of Global Variables Except for symbolic constants and prototypes, global variables should almost never be used By making a variable global, you instantly destroy the safeguards C provides to make functions independent and insulated from each other Using global variables can be especially di

10、sastrous in large programs with many user-created functions Because a global variable can be accessed and changed by any function following the global declaration, it is a time-consuming and frustrating task to locate the origin of an erroneous valueA First Book of ANSI C, Fourth Edition13Variable S

11、torage Class In addition to the space dimension represented by its scope, variables also have a time dimension Called the variables “l(fā)ifetime” Where and how long a variables storage locations are kept before they are released can be determined by the storage class of the variable auto, static, exter

12、n, and registerA First Book of ANSI C, Fourth Edition14Variable Storage Class (continued) Examples:auto int num;static int miles;extern int price;register int dist;auto float coupon;static float yrs;extern float yld;auto char inKey;A First Book of ANSI C, Fourth Edition15Local Variable Storage Class

13、es Local variables can only be members of the auto, static, or register storage classes auto is the default class used by C The term auto is short for automatic Storage for automatic local variables is automatically reserved each time a function declaring automatic variables is called As long as the

14、 function has not returned control to its calling function, all automatic variables local to the function are “alive”; that is, storage for the variables is availableA First Book of ANSI C, Fourth Edition16Output is:The value of the automatic variable num is 0The value of the automatic variable num

15、is 0The value of the automatic variable num is 0Local Variable Storage Classes (continued)A First Book of ANSI C, Fourth Edition17Local Variable Storage Classes (continued) A local variable declared as static causes the program to keep the variable and its value even when the function that declared

16、it is done Once created, local static variables remain in existence for the life of the program Static variables are not initialized at run-time The initialization of static variables is done only once, when the program is first compiled Some compilers initialize local static variables the first tim

17、e the definition statement is executed rather than when the program is compiledA First Book of ANSI C, Fourth Edition18Output is:The value of the static variable num is now 0The value of the static variable num is now 1The value of the static variable num is now 2Local Variable Storage Classes (cont

18、inued)A First Book of ANSI C, Fourth Edition19Local Variable Storage Classes (continued) Register variables have the same time duration as automatic variables register int time; Registers are high-speed storage areas physically located in the computers processing unit Application programs rarely, if

19、 ever, should use register variables Variables declared with the register storage class are automatically switched to auto if the compiler does not support register variables or if the declared register variables exceed the computers register capacityA First Book of ANSI C, Fourth Edition20Global Va

20、riable Storage Classes Global variables are created by declaration statements external to a function They exist until the program in which they are declared is finished executing Global variables are declared static or extern extern int sum; static float yield; The purpose of the extern storage clas

21、s is to extend the scope of a global variable declared in one source code file into another source code fileA First Book of ANSI C, Fourth Edition21Global Variable Storage Classes (continued)A First Book of ANSI C, Fourth Edition22Global Variable Storage Classes (continued)A First Book of ANSI C, Fo

22、urth Edition23Global Variable Storage Classes (continued) Declaration statements containing the word extern do not create new storage areas; they only extend the scope of existing global variables The static global class is used to prevent the extension of a global variable into a second file The sc

23、ope of a global static variable cannot be extended beyond the file in which it is declared Provides some privacy for static global variablesA First Book of ANSI C, Fourth Edition24Pass by Reference In pass by value, a called function receives values from its calling function, stores the passed value

24、s in its own local parameters, manipulates these parameters appropriately, and directly returns, at most, a single value Passing an address is referred to as a function pass by reference, because the called function can reference, or access, the variable using the passed address Also referred to as

25、a call by reference when the term applies only to those parameters whose addresses have been passedA First Book of ANSI C, Fourth Edition25Passing Addresses to a Function Output is:num = 22The address of num is 124484A First Book of ANSI C, Fourth Edition26Storing Addresses numAddr = # A var

26、iable that can store an address is known as a pointer variable or pointerA First Book of ANSI C, Fourth Edition27Storing Addresses (continued)A First Book of ANSI C, Fourth Edition28Storing Addresses (continued)A First Book of ANSI C, Fourth Edition29Using Addresses Indirection operator: * *numAddr

27、means the variable whose address is stored in numAddr Or, the variable pointed to by numAddr When using a pointer, the value obtained is always found by first going to the pointer for an address; this is called indirect addressingA First Book of ANSI C, Fourth Edition30Using Addresses (continued)A F

28、irst Book of ANSI C, Fourth Edition31Declaring and Using Pointers In declaring a pointer variable, C requires that we also specify the type of variable that is pointed to int *numAddr; This declaration can be read in a number of ways: as the variable pointed to by numAddr is an integer, or as numAdd

29、r points to an integerA First Book of ANSI C, Fourth Edition32Output is:The address stored in milesAddr is 1244872The value pointed to by milesAddr is 22The value in miles is now 158Declaring and Using Pointers (continued)A First Book of ANSI C, Fourth Edition33Declaring and Using Pointers (continue

30、d)A First Book of ANSI C, Fourth Edition34Passing Addresses to a FunctionA First Book of ANSI C, Fourth Edition35Passing Addresses to a Function (continued) Sample run of Program 7.6:Enter a number: 24.6The address that will be passed is 124484The address received is 124484The value pointed to by xn

31、um is: 24.60A First Book of ANSI C, Fourth Edition36Passing Addresses to a Function (continued)A First Book of ANSI C, Fourth Edition37Add 20.2 to the value of the variable pointed to by xnumPassing Addresses to a Function (continued)A First Book of ANSI C, Fourth Edition38Returns multiple valuesPas

32、sing Addresses to a Function (continued)A First Book of ANSI C, Fourth Edition39Case Study: Swapping Values A common programming requirement is the sorting of both numeric values and text, such as names, in either ascending (increasing) or descending (decreasing) order Typically accomplished by comp

33、aring two values and then switching values if they are not in the correct orderA First Book of ANSI C, Fourth Edition40Requirements Specification Write a C function that exchanges the values in two single-precision variables of its called function Thus, if the function has access to two variables of

34、 its calling function, the called function should switch the values in these variablesA First Book of ANSI C, Fourth Edition41Analyze the Problem Input (arguments of the function): two addresses, of the two variables whose values are to be exchanged Output: change the values in the calling function

35、using passed addresses Swapping the values of two variables is accomplished using the following algorithm: Store the first variables value in a temporary location Store the second variables value in the first variable Store the temporary value in the second variableA First Book of ANSI C, Fourth Edi

36、tion42Analyze the Problem (continued)A First Book of ANSI C, Fourth Edition43Analyze the Problem (continued)A First Book of ANSI C, Fourth Edition44Code the FunctionA First Book of ANSI C, Fourth Edition45Code the Function (continued)A First Book of ANSI C, Fourth Edition46Code the Function (continu

37、ed)A First Book of ANSI C, Fourth Edition47Code the Function (continued)A First Book of ANSI C, Fourth Edition48Test and Debug the Program The following sample run was obtained using Program 7.10, which completes the verification:Enter two numbers: 20.5 6.25Before the call to swap():The value in fir

38、stnum is 20.50The value in secnum is 6.25After the call to swap():The value in firstnum is 6.25The value in secnum is 20.50A First Book of ANSI C, Fourth Edition49Recursion Functions that call themselves are referred to as self-referential or recursive functions When a function invokes itself, the p

39、rocess is called direct recursion A function can invoke a second function, which in turn invokes the first function; this type of recursion is referred to as indirect or mutual recursionA First Book of ANSI C, Fourth Edition50Mathematical RecursionThe definition for n! can be summarized by the follo

40、wing statements:0! = 1n! = n * (n-1)! for n = 1This definition illustrates the general considerations that must be specified in constructing a recursive algorithm:1. What is the first case or cases?2. How is the nth case related to the (n-1) case?A First Book of ANSI C, Fourth Edition51Mathematical

41、Recursion (continued) In pseudocode, the processing required isIf n = 0factorial = 1ElseFactorial = n * factorial(n - 1) In C, this can be written asint factorial(int n) if (n = 0) return (1); else return (n * factorial(n-1);A First Book of ANSI C, Fourth Edition52Mathematical Recursion (continued)A

42、 First Book of ANSI C, Fourth Edition53How the Computation is PerformedA First Book of ANSI C, Fourth Edition54How the Computation is Performed (continued)A First Book of ANSI C, Fourth Edition55How the Computation is Performed (continued)A First Book of ANSI C, Fourth Edition56Recursion versus Iter

43、ation The recursive method can be applied to any problem in which the solution is represented in terms of solutions to simpler versions of the same problem Any recursive function can be written in a nonrecursive manner using an iterative solutionint factorial(int n) int fact; for(fact = 1; n 0; n-) fact = fact * n; return (fact);A First Book of ANSI C, Fourth Edition57Common Programming Errors Using the same na

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論