A First Book of ANSI C Fourth Edition

上传人:e****s 文档编号:243356231 上传时间:2024-09-21 格式:PPT 页数:60 大小:1.36MB
返回 下载 相关 举报
A First Book of ANSI C Fourth Edition_第1页
第1页 / 共60页
A First Book of ANSI C Fourth Edition_第2页
第2页 / 共60页
A First Book of ANSI C Fourth Edition_第3页
第3页 / 共60页
点击查看更多>>
资源描述
A First Book of ANSI C, Fourth Edition,1,Click to edit the title text format,Click to edit the outline text format,Second Outline Level,Third Outline Level,Fourth Outline Level,Fifth Outline Level,Sixth Outline Level,Seventh Outline Level,Eighth Outline Level,Ninth Outline Level,A First Book of ANSI C,Fourth Edition,Chapter 7,Modularity Using Functions: Part II,Objectives,Variable Scope,Variable Storage Class,Pass by Reference,Case Study: Swapping Values,Recursion,Common Programming and Compiler Errors,Variable 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”,Variable Scope (continued),Variable 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 any function,Variable Scope (continued),Variable Scope (continued),Variable Scope (continued),Program 7.1 produces the following output,From main(): firstnum = 10,From main(): secnum = 20,From valfun(): firstnum = 10,From valfun(): secnum = 30,From main() again: firstnum = 40,From main() again: secnum = 20,While a function is executing, only the storage area for the variables and parameters created by this function are automatically accessed,Variable 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 variable,Variable Scope (continued),When 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 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 it,Misuse 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 disastrous 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 value,Variable Storage Class,In addition to the space dimension represented by its scope, variables also have a time dimension,Called the variables “lifetime”,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,extern, and,register,Variable 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;,Local Variable Storage Classes,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 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 available,Output is:,The value of the automatic variable num is 0,The value of the automatic variable num is 0,The value of the automatic variable num is 0,Local Variable Storage Classes (continued),Local 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 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 time the definition statement is executed rather than when the program is compiled,Output is:,The value of the static variable num is now 0,The value of the static variable num is now 1,The value of the static variable num is now 2,Local Variable Storage Classes (continued),Local 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 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 capacity,Global Variable 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 class is to extend the scope of a global variable declared in one source code file into another source code file,Global Variable Storage Classes (continued),Global Variable Storage Classes (continued),Global 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 scope of a global static variable cannot be extended beyond the file in which it is declared,Provides some privacy for static global variables,Pass by Reference,In,pass by value, a called function receives values from its calling function, stores the passed values 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 a,call by reference,when the term applies only to those parameters whose addresses have been passed,Passing Addresses to a Function,Output is:,num = 22,The address of num is 124484,Storing Addresses,numAddr = ,A variable that can store an address is known as a,pointer variable,or,pointer,Storing Addresses (continued),Storing Addresses (continued),Using Addresses,Indirection operator: *,*numAddr,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 addressing,Using Addresses (continued),Declaring 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,numAddr,points to an integer,Output is:,The address stored in milesAddr is 1244872,The value pointed to by milesAddr is 22,The value in miles is now 158,Declaring and Using Pointers (continued),Declaring and Using Pointers (continued),Passing Addresses to a Function,Passing Addresses to a Function (continued),Sample run of Program 7.6:,The address that will be passed is 124484,The address received is 124484,Passing Addresses to a Function (continued),Add 20.2 to the value of the variable pointed to by,xnum,Passing Addresses to a Function (continued),Returns multiple values,Passing Addresses to a Function (continued),Case 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 comparing two values and then switching values if they are not in the correct order,Requirements 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 its calling function, the called function should switch the values in these variables,Analyze 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 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 variable,Analyze the Problem (continued),Analyze the Problem (continued),Code the Function,Code the Function (continued),Code the Function (continued),Code the Function (continued),Test and Debug the Program,The following sample run was obtained using Program 7.10, which completes the verification:,Before the call to swap():,After the call to swap():,Recursion,Functions that call themselves are referred to as,self-referential,or,recursive,functions,When a function invokes itself, the process 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 recursion,Mathematical Recursion,The definition for n! can be summarized by the following statements:,0! = 1,n! = n * (n-1)! for n = 1,This definition illustrates the general considerations that must be specified in constructing a recursive algorithm:,What is the first case or cases?,How is the,n,th case related to the,(n-1),case?,Mathematical Recursion (continued),In pseudocode, the processing required is,If n = 0,factorial = 1,Else,Factorial = n * factorial(n - 1),In C, this can be written as,int factorial(int n),if (n = 0),return (1);,else,return (n * factorial(n-1);,Mathematical Recursion (continued),How the Computation is Performed,How the Computation is Performed (continued),How the Computation is Performed (continued),Recursion versus Iteration,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 solution,int factorial(int n),int fact;,for(fact = 1; n 0; n-),fact = fact * n;,return (fact);,Common Programming Errors,Using the same name for a local variable that has been used for a global variable,Becoming confused about whether a parameter (or variable),contains,an address or,is,an,address,Declaring a pointer as a function parameter and then forgetting to place the address operator, &, before the argument passed to the function when it is called,Forgetting to specify the initial case when a recursive function is defined,Common Compiler Errors,Summary,Every variable used in a program has,scope, which determines where the variable can be used,Every variable has a class,Every variable has a data type, a value, and an address,A pointer is a variable or parameter that is used to store the address of another variable,If a parameter or variable is a pointer, then the indirection operator, *, must be used to access the variable whose address is stored in the pointer,Summary (continued),The address of a variable can be passed to a function,When a called function receives an address, it has the capability of directly accessing the respective calling functions variable,A recursive solution is one in which the solution can be expressed in terms of a “simpler” version of itself,If a problem solution can be expressed repetitively or recursively with equal ease, the repetitive solution is preferable because it executes faster and uses less memory,
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 商业管理 > 商业计划


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!