《C语言课程设计案例精编》课件 4_第1页
《C语言课程设计案例精编》课件 4_第2页
《C语言课程设计案例精编》课件 4_第3页
《C语言课程设计案例精编》课件 4_第4页
《C语言课程设计案例精编》课件 4_第5页
已阅读5页,还剩88页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 4:Functions Instructor : Xiang XieOutline4.1Basics of Function 1. Program structure2. Function Definition3. Function Declaration4. Function Call and Return 4.2 ArgumentsCall by Value 4.3 Function Returning Void4.4 Scope Rules and Variables 1. Scope Rules2. Variables3. Initialization4.5 Recur

2、sion 4.6 The C Preprocessor and Standard Library 1 Program StructurelAny C program consists of functions. Every C program contains at least a function called main, which declares the start point of the program.lA function provides a convenient way to encapsulate (封装封装) some computation, which can th

3、en be used without worrying about its implementation. lWith properly designed functions, it is possible to ignore how a job is done; knowing what is done is sufficient.Module_3Module_2_2Module_2Module_1_1Main moduleModule_1Module_2Module_3Print Diamond * * * * * * * * * * * * * * * * * * * * * * * *

4、 *Print upper-triangle * * * * * * * * * * * * * * * *Print lower-triangle * * * * * * * * *Print “*”Module_1Module_4Module_5Main module* * * * * * * * * * * * * * * * * * * *Example 8_1.1:design a program to implement the exponentiation (求幂求幂) operation, e.g. 2x and (-3)x? #include main() int x, i,

5、base1,base2,p1,p2; base1=2; base2=-3; scanf(“%d”,&x); p1=1; p2=1; for (i=1; i=x; i+) p1=p1*base1; p2=p2*base2; printf(“%d%dn”, p1,p2);#include int power (int base, int n);main() int i; scanf(“%d”,&x); printf(“%d%dn”, power(2,x), power(-3,x);int power (int base, int n) int i, p=1; for (i=1;iy

6、?pow(x,y):pow(y,x); return k; Function headFunction bodylA function definition has this form: return-type function-name ( parameter list ) parameter declarations declarations statements lExplanation:Parameter declaration is optional, which can be implemented in the parameter list.Two brackets (括号括号)

7、 show the start and the end of the function. 1Function Definition 1Function Definition (con.) lAccording to the function definition, is it reasonable? dummy ( ) lAbove is the minimal function, which does nothing and return nothing.lSometimes, a do-nothing function like this is useful as a place hold

8、er (keeper) during program development.C generally uses parameter list - formal argument (形参形参) for variable names in a function definition, and actual argument (实参实参) for the value used in a call of the function. The terms formal argument (形参形参) and actual argument (实参实参) are sometimes used for the

9、 same distinction.Commas (,) are used as the separators among parameters; 1Function Definition (con.) 1Function Definition (con.) #include int power (int base, int n);main() int x; scanf(“%d”,&x); printf (“%d %dn”, power(2,x), power(-3,x) ); int power (int base, int n) int i, p=1; for (i=1; i=n;

10、 i+) p=p*base; return p; FunctionDefinitionReturn-typeFunction nameParameter list(Formal arguments)Actual argumentsReturn-valueint power (base, n)int base, n; int i, p=1; for (i=1; i=n; i+) p=p*base; return p; #include int power (int base, int n);main() int x; scanf(“%d”,&x); printf(“%d%dn”, pow

11、er(2,x), power(-3,x);int power (int base, int n) int i, p=1; for (i=1;i0; -x ) y *= x; return (y);Function declarationFunction callFunction definitionm is argumentparameter listFunction returnmain ( ) mm = facto( m );facto ( x ) return (y );CallReturnAnother writing way!long facto (int x) long y; fo

12、r ( y=1; x0; -x ) y *= x; return (y);main( ) int m; long mm; scanf(%d, &m); mm = facto( m ) printf(%d!=%ld.n, m, mm);Example_4.2: Calculate the factorial (阶乘阶乘) of m.main ( ) int a,b,c; scanf(%d,%d,&a,&b); c=max(a,b); printf(“max=%dn”, c); int max(int x, int y) int z; if (xy) z=x; else z

13、=y; return(z);/* 1*/* 2*/* 3*/* 4*/* 5*/* 6*/* 7*/*11*/*12*/*13*/*14*/*15*/*16*/*17*/store original values,goto 11.a xb yReturn valueRelease originalvaluesExample 8_1.3:Compare two integers, output the bigger.lTwo methods of function return: Return from the called function to its caller when execute

14、 return statement. if no return statement exits, return from the called function to its caller when execute the furthest right-bracket in the called function.lTwo forms of return statement: return ;-Means a function returns to its caller without value. return ( expression ) ;-Means the result value

15、of called function return to its caller.& Function Return:lRules for return value: Except void-type (空类型空类型) function , any function should have, and only have one return value. When define a function, if its return value is int, type of function could be omitted. for example: max (int x, int y)

16、 int z; z = x y ? x : y ; return (z); When define a function, if its return value is not int, type of function should be declared. & Function Return (con.):main() int a,b,c; scanf(%d,%d, &a, &b); c=max(a,b); printf(max=%d,%d,%dn,c,a,b);int max (int x, int y) int z; if (xy) z=x; else z=y;

17、 printf(z=%d,%d,%dn,z,x,y); return(z);Input: 6,7Output: z=7,6,7 max=7,6,7Error information:Undefined symbol z in function main.printf(max=%d,%d,%dn,z,x,y);Input: 6, 8Output:z = 8,8max = 8, 14Input: 6, 8Output:z = 8,8max = 8, 10 #include main() int a,b,c; scanf(%d,%d, &a, &b); c=max(a,b); pri

18、ntf(max=%d,%dn,c,a+b); int max(int x, int y) int z,a=3,b=5; if (xy) z=x; else z=y; printf(z=%d,%dn, z, a+b); return(z); int a,b,c,z=10;printf(max=%d,%dn,c,z);main( ) int m, n; long cmn, facto( ); scanf (%d%d, &m, &n); cmn = facto(m) / (facto(n) * facto(m-n) ); printf (The combination is %ldn

19、, cmn);long facto (int x) long y; for ( y=1; x0; -x ) y *= x; return (y);Example 8_1.4: Calculate C (m ,n) = m! / (n!* (m-n) !)1Function Call and Return (con.) lNested function call:mainmain call function A;A; function function A A call function B; function Bfunction B callcallreturnreturn1Methods a

20、bout transfer data between two functions: In C, there are three methods to transfer data. They are:1. Return values;2. Arguments & parameters;3. Global variables (全局变量全局变量). Return values: the most simple method, each time only can transfer one value according to the return (expression) statemen

21、t.Discuss in section_4Arguments & parameters:2In C, all function arguments are passed “by value”. This means that the called function is given the values of its arguments in temporary variables (local copy) rather than the originals.Rules about passed by valueWhen call a function, values of argu

22、ments are copied to the parameters.The called function cannot directly alter (改变改变) a variable in the calling function; it can only alter its private, temporary copy.Argument could be an expression. Before passed, calculate the value of the expression first.main ( ) int a, b; a=5; b=10; printf (“Bef

23、ore swap, a=%d, b=%dn, a, b); swap (a, b); printf (“After swap, a=%d, b=%dn, a, b);swap (int x, int y) int temp; temp=x; x=y; y=temp; printf (“In swap, x=%d, y=%dn, x, y);Example 8_2.1: Exchange values of two variables by using sub-function.RunningBefore swap, a=5, b=10In swap, x=10, y=5After swap,

24、a=5, b=10main ( ) a = 5 ; b = 10 ; swap (a , b) ;Program execution processswap (int x, int y) temp = x ; x = y ; y = temp ;510Argument aArgument b510Parameter xParameter yVariabletempcopycopy temp = xx x= =y y y y = = temptemp105 5 Execute swap()&Features about passed by value:l Advantage: 被调用的函

25、数被调用的函数不可能改变不可能改变调用函数中变量的值,调用函数中变量的值,而而只能改变只能改变它的局部的它的局部的临时副本临时副本。这样就可以避。这样就可以避免被调用函数的操作对调用函数中的变量可能产免被调用函数的操作对调用函数中的变量可能产生的副作用。生的副作用。l Disadvantage: 在值传递方式下,每个形式参数在值传递方式下,每个形式参数仅能传递仅能传递一个数一个数据据,当需要在函数之间,当需要在函数之间传递大量数据传递大量数据时,值传递时,值传递方式显然不适用。方式显然不适用。To a variable, there are three essential attributes

26、:1.Variable name;2.Variable value;3.Variable address.Arguments & parameters (con.):2In C, arguments also could be passed “by address”. 25X1008972程序运行时,要将变量的值保存在计算机的存储单程序运行时,要将变量的值保存在计算机的存储单元中,每个存储单元都有元中,每个存储单元都有唯一唯一的内存地址。变量的内存地址。变量在在内存中占据的存储单元的地址内存中占据的存储单元的地址就是就是变量的地址变量的地址。&Some important co

27、ncepts:2Two terms :1.Direct access (直接访问直接访问) : means access (存取存取) value according to the variable name. 2.Indirect access (间接访问间接访问) : means access value according to the variable address.2Two unary pointer operators:1. & : gives the address of an object.2. * : accesses the object the pointer

28、points to.Example: int x = 2 , *px ; Analysis:x is a common variable, px is a pointer variable.px = &x ;gives address of variable of x tothe pointer variable px; or px pointsto the variable x.x = 10 ; *px = 10 ;pxxDirect accessIndirect access210Short Summary about arguments transfer between two

29、functions:Passed by value: according to common variablesPassed by address: according to variablesNotice!lWhen passed by address, address of variable is argument in calling function; pointer variable works as parameter in called function.lType of argument should be same with the object type the point

30、er points to.In another word, actually pointers are passed between functions.main ( ) int a, b; a=5; b=10; printf (“Before swap, a=%d, b=%dn, a, b); swap (&a, &b); printf (“After swap, a=%d, b=%dn, a, b);swap (int *px, int *py) int temp; temp= *px; *px=*py; *py=temp; printf (“In swap, x=%d,

31、y=%dn, *px, *py);Example 8_2.2: Exchange values of two variables by using addresses.RunningBefore swap, a=5, b=10In swap, x=10, y=5After swap, a=10, b=5main ( ) a = 5 ; b = 10 ; swap (&a , &b) ;swap (*px, *py) temp = *px ; *px = *py ; *py = temp ;Program execution process510Variable aVariabl

32、e b&a&bparameter pxparameter py&a&b Variable temp temp = * *px * *px = * *py * *py = temp105 5Execute swap()lVoid-type function means return no value (void).lThe form: void function-name ( parameter list) . lNotice: 1. void means return without value, never means no return!(return;)2

33、. There is no difference between void function definition and called function definition with return value.3. However; When call a void-type function, only can use an isolate statement to do, cannot put it inside expression to call like other called functions with return values.& Data types of v

34、ariables: char int float double 静态存储(存放在内存静态存储区)静态存储(存放在内存静态存储区)占用固定存储单元,变量的值始终保存占用固定存储单元,变量的值始终保存变量生存期为整个程序变量生存期为整个程序 动态存储(存放在内存动态存储区)动态存储(存放在内存动态存储区)在函数调用时才临时分配存储单元在函数调用时才临时分配存储单元调用结束立即释放,不保存变量的值调用结束立即释放,不保存变量的值动态存储的动态存储的变量生存期为变量生存期为函数调用期间函数调用期间1. 变量生存期变量生存期 (Variable lifetime) 变量值保留的期限变量值保留的期限变量生

35、存期与存储区域相关变量生存期与存储区域相关& Variables Scope means the region, where the variable could be accessed. It could be:A function;A file;A program.2. 变量的作用域变量的作用域 (Variables Scope ) 变量的有效范围变量的有效范围 局部变量局部变量 (local variable)在函数或复合语句内部定义的变量。其作用在函数或复合语句内部定义的变量。其作用域在定义它的函数或复合语句内部。域在定义它的函数或复合语句内部。f ( ) int x1=3;

36、int x2=1; printf(“x2=%dn”,x2); / /* *x2=1x2=1* */ / printf(“x2=%dn”,x2); printf(“ x1=%dn”,x1); / /* *x1=3x1=3* */ /X2 scopeX1 scopef ( )int x=3; / /* *local variable x in f()local variable x in f()* */ / int x=2; / /* *local variable x in statementlocal variable x in statement* */ / printf(“* x=%dn”

37、,x); printf(“* x=%dn”,x);main( )int x=10; / /* *local variable x in mainlocal variable x in main* */ / printf(“1: x=%dn”,x); f( ); printf(“2: x=%dn”,x);Output:1: x=10*x=2*x=32: x=10int x=100; / /* *global variableglobal variable* */ /f1( ) int x=50; / /* *local variable f1()local variable f1()* */ /

38、 printf(“f1,x=%dn”,x); main( ) x+; / /* *global variableglobal variable* */ / f1( ); printf(“main,x=%dn”,x); 全局变量全局变量 (global variable)在函数外定义的变量。其作用域在函数外定义的变量。其作用域: 从定义点到从定义点到文件尾。文件尾。Scope of global variable xOutput: f1,x=50 main,x=101l全局变量与局部变量可以重名,不同全局变量与局部变量可以重名,不同函数内的局部变量也可以重名,它们互函数内的局部变量也可以重名,它

39、们互不影响。不影响。l若若全局变量与局部变量同名,则在局全局变量与局部变量同名,则在局部变量部变量作用域内作用域内全局变量不起作用。全局变量不起作用。& The variable storage classes are: Automatic variable Register variable External variable Static variable& Form of variable declaration:specifier qualifier type list of variables ;autoregister externstaticStorage-cla

40、ss-specifier存储类型说明符存储类型说明符lIt is the most popular variable, its form:auto data-type variable-list ;lThe specifier auto could be omitted because automatic variable are default (默认的默认的) in C. For example: auto int x ; int x ;lExplanation:1.Automatic variable declaration must be inside a function.2.All

41、 parameters are automatic variables.Automatic variable (自动变量自动变量)lAutomatic variables scope: within function.lIn fact, all automatic variables are local variables (局部变量局部变量). They exist only when the function is called, and disappear when the function is exited. Their values could only be accessed b

42、y function which declares them.lAdvantage: According to the local characteristic, we can apply automatic variables with same names among different functions (no effect).Automatic variable (con.)Example 5_4.1: Analyses the result of following program.#include void f1( ), f2( ) ;main( ) int x = 1; f1(

43、 ); f2(x); printf (x=%d n, x);void f1 ( ) int x = 3; printf (x=%dt, x);void f2 ( int x ) +x; printf (x=%dt, x); Running:X = 3X = 2X = 1l Difference between common variable and register variable :The former stores in the memory;The latter store in the register which is inside the CPU.l Advantage of r

44、egister variable: variables will be heavily used could be declared as register variable because of its faster access speed.Register variable (寄存器变量寄存器变量)lExternal variable must be defined once outside of any functions. lExternal variable is the global variable to all functions in a program. In anoth

45、er word, any function can access it.lThe variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.External variable (外部变量外部变量)Local variableglobal variableautomat

46、ic variableexternal variableSome rules about external variablelNormally place definitions of all external variables at the beginning of the source file, and then omit all extern declarations. lIf the definition of an external variable occurs in the source file before its use in a particular function

47、, then the extern can be omitted. lIf the program is in several source files, and a variable is defined in file1 and used in file2 and file3, then extern declarations are needed in file2 and file3.lIf a large number of variables must be shared among functions, external variables are more convenient

48、and efficient than long argument lists.lExternal variables are also useful because of their greater scope and lifetime. -scope: all functions;-lifetime: permanent (永久的永久的).lIf no explicit (明确的明确的) value at the beginning, system will assign zero (0) to the external variable.The differences between ex

49、ternal variable and automatic variablelExternal variable:1.Lifetime: exists permanently to retain value from one function to invocation to the next.2.Scope(作用域作用域): outside of any functions.3.If no initialization: be assigned a zero (0) by system. lAutomatic variable:1.Lifetime: exists only when the

50、 function is entered, and disappear when the function is left.2.Scope: inside a function.3.If no initialization: no value at the beginning.1.c : int x; / /* *external variableexternal variable* */ / extern void f1( ); / /* *f1 function in 2.cf1 function in 2.c* */ / void f2( ) int x=10; / /* *automa

51、ticautomatic* */ / printf(“f2,x=%dn”,x); main( ) x=1; f1( ); f2( ); printf(“x=%dn”,x); 2.c :extern int x; / /* *external variable in external variable in 1.c 1.c * */ / void f1( ) x+; printf(“f1,x=%d”,x); Output: f1,x=2 f2,x=10 x=2int x = 0; void addone( ); void subone( );main ( ) x = 1; printf (x b

52、egin: %dn, x); addone( ); subone( ); subone( ); addone( ); addone( ); printf (x end: %dn, x);void addone ( ) x +; printf (add 1: %dn, x); void subone ( ) x -; printf (sub 1: %dn, x); RunningX begin: 1add 1: 2sub 1: 1sub 1: 0add 1: 1add 1: 2X end: 2Example 8_4.2: Analyze the result of following progr

53、am./* file1.c */int x = 10; int y = 10;extern void sub( ); void add ( ) y = 10+x; x *= 2; main ( ) x += 5; add( ); sub( ); printf (x=%d; y=%dn, x, y);/* file2.c */void sub( ) extern int x; x - = 5;Example 8_4.3: Analyze the result of following program.Runningx= 25 ; y= 25/* file1.c */int x = 10; int

54、 y = 10;extern void sub(); void add ( ) int y = 5; y = 10 + x; x *= 2; printf(add:y=%dn, y); main ( ) x += 5; add(); sub(); printf(main:x=%d;main:y=%dn,x,y); Example 8_4.4: Analyze the result of following program./* file2.c */extern int x; void sub ( ) int y = 5; x - = y; printf(sub:y=%dn, y); Runni

55、ngadd: y=25; sub: y= 5main: x=25; main: y=10lBy prefixing the normal declaration with the word static, we can specify static variable.lIt can be separated into two types:Static variable (静态变量静态变量)external static variableinternal static variable2 Similarity between static variable and external variab

56、le:-Both provide permanent storage, and initialized by compiling system. 2 Difference between external static variable and external variable:1. The former is in effect within the source file.2. The latter is in effect within the program.Static variable (con.)2 Similarity between internal static vari

57、able and automatic variable: -Both are effects within a particular function.2 Difference between internal static variable and automatic variable:1. The former provides permanent storage.2. The latter provides temporary storage.Static variable (con.)/* file1.c */static int x = 2; int y = 3; extern vo

58、id add2( ); void add1( );main ( ) add1( ); add2( ); add1( ); add2( ); printf (x=%d; y=%dn, x, y); void add1( ) x += 2; y += 3; printf (in add1 x=%dn, x); Example 8_4.5: Analyze the result of following program./* file2.c */static int x=10;extern int y; void add2( ) x += 10; y += 2; printf (in add2 x=

59、%dn, x); RunningIn add1 x= 4In add2 x= 20In add1 x= 6In add2 x= 30 x= 6 ; y=13#include void inc1( ), inc2( );main ( ) inc1( ); inc1( ); inc1( ); inc2( ); inc2( ); inc2( );void inc1( ) int x = 0; x+; printf (in inc1 x=%dn, x);void inc2( ) static int x=0; x+; printf (in inc2 x=%dn, x);RunningIn inc1 x

60、=1In inc1 x=1In inc1 x=1In inc2 x=1In inc2 x=2In inc2 x=3Example 8_4.6: Analyze the result of following program.& Initialization (变量初始化变量初始化)2Rules about initialization of the various storage classes:lIn the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero (0) by default (compiling system); automatic and register variables have undefined initial values.lScalar (标量标量) va

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论