C程序设计英文课件:CHAPTE 4 Functions and Program Structure_第1页
C程序设计英文课件:CHAPTE 4 Functions and Program Structure_第2页
C程序设计英文课件:CHAPTE 4 Functions and Program Structure_第3页
C程序设计英文课件:CHAPTE 4 Functions and Program Structure_第4页
C程序设计英文课件:CHAPTE 4 Functions and Program Structure_第5页
已阅读5页,还剩83页未读 继续免费阅读

下载本文档

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

文档简介

1、CHAPTE 4mainfunc1func2func3func6func7func8func4func5.C语言是通过函数来实现模块化程序设计的。所以较大的C语言应用程序,往往是由多个函数组成的,每个函数分别对应各自的功能模块。Contents1. Basics of Functions2. Functions Returning Non-integers3. External Variables4. Static Variables5.Register Variables6. Header Files7. Block Structure8. Initialization9. Recursio

2、n10. The C Preprocessor4.1 Basics of Functionsreturn_type function_name (argument declaration)declarations and statementsfor example:int max( int x,int y)int z;z=xy?x:y;return(z); 4.1 Basics of FunctionsThe definition of function Note1:No Argument Functionreturn_type function_name ( )declarations an

3、d statementsfor example:int dummy( ). 4.1 Basics of FunctionsThe definition of function Note2: if return type is omitted, int is assumedmy_function(int c).int4.1 Basics of FunctionsNote3: dummy()The definition of function 合法标识符函数返回值类型缺省int型无返回值void函数体函数类型 函数名(形参类型说明表)说明部分语句部分4.1 Basics of FunctionsT

4、he definition of function return_type function_name (argument declaration).return (expression);Note: any expression can be followed return statement expression will be converted to the return_type parentheses(optional ) are often used around 表达式的数据类型将被强制转换为函数的返回类型 表达式一般放在一对圆括号中4.1 Basics of Function

5、sThe Return Statement of function No return valuevoid printstar ( )printf(“*”);Note: use void key word to declare the function which no return value. (使用void关键字表示函数没有返回值)4.1 Basics of FunctionsThe Return Statement of function 形式: return(表达式);或 return 表达式;或 return;功能:使程序控制从被调用函数返回到调用函数中,同时把返回值带给调用函数说

6、明:若无return语句,遇 时,自动返回调用函数若函数类型与return语句中表达式值的类型不一致,按前者为准,自动转换-函数调用转换void型函数用来明确表明函数不带回任何值例 无返回值函数void swap(int x,int y ) int temp; temp=x; x=y; y=temp;4.1 Basics of FunctionsThe Return Statement of function 例 函数返回值类型自动转换为函数类型#includemain() float a,b; int c; int max(float x,float y); scanf(%f,%f,&a,&

7、b); c=max(a,b); printf(Max is %dn,c);max(float x, float y) float z; z=xy?x:y; return(z);运行结果:1.5, 4.7Max is 44.1 Basics of Functions说明:实参必须有确定的值形参必须指定类型形参与实参类型一致,个数相同若形参与实参类型不一致,自动按形参类型转换 函数调用转换参数传递方式为值传递方式:函数调用时,为形参分配单元,并将实参的值复制到形参中;调用结束,形参单元被释放,实参单元仍保留并维持原值。特点:形参与实参占用不同的内存单元;单向传递形式参数与实际参数形式参数:定义函数

8、时函数名后面括号中的变量名实际参数:调用函数时函数名后面括号中的表达式 c=max(a,b); (main 函数) (max 函数)max(int x,int y) int z; z=xy?x:y; return(z); 例 比较两个数并输出大者#include (c7_2.c)main() int a,b,c; int max(int x,int y); scanf(%d,%d,&a,&b); c=max(a,b); printf(Max is %d,c);max(int x,int y) int z; z=xy?x:y; return(z);形参实参4.1 Basics of Functi

9、ons711x:y:调用前:调用结束:711x:y:例 交换两个数#include main() int x=7,y=11; printf(x=%d,ty=%dn,x,y); printf(swapped:n); swap(x,y); printf(x=%d,ty=%dn,x,y);swap(int a,int b) int temp; temp=a; a=b; b=temp;调用:711a:b:711x:y:swap:711x:y:117a:b:temp运行结果:x=7, y=11 swapped: x=7, y=11值传递方式,单向传递Example:说明实参与形参的关系main() in

10、t s(int n) int n; printf(input numbern); scanf(%d,&n); s(n); printf(n=%dn,n);int s(int n) int i; for(i=n-1;i=1;i-) n=n+i; printf(n=%dn,n);4.1 Basics of FunctionsResult:n=5050n=100 Callingsyntax:function_name(actual argument list)function statement:函数构成的语句printstar( );function expression:函数构成的表达式c=ma

11、x(a,b);function argument: 函数作为参数c=max(a,max(b,c);printf(“%d”,max(5,8);format实参序列4.1 Basics of Functions Function declaration(函数的声明)syntax:return_type function_name(argument declaration)main() int max(int a,int b);(函数原型).int max(int x, int y) return (xy)?x:y;main() int max(int, int);int max(int x, in

12、t y) . Function declarationsyntax:return_type function_name( )need not declaration:return type is int or char;function defined before used;有两种情况函数不需要声明: 1、函数类型为整型或字符型 2、函数定义在使用之前4.1 Basics of Functions#include long sum(int a, int b);long factorial(int n);main() int n1,n2; long a; scanf(%d,%d,&n1,&n2

13、); a=sum(n1,n2); printf(a=%1d,a);long sum(int a,int b) long c1,c2; c1=factorial(a); c2=factorial(b); return(c1+c2);long factorial(int n) long rtn=1; int i; for(i=1;i=n;i+) rtn*=i; return(rtn);long sum(int a,int b);long factorial(int n);文件包含编译预处理命令函数声明函数定义函数调用函数调用函数返回值形参实参 Lib function declarationsyn

14、tax:#include #include main().printf(.);#include main().for(i=0;isspace(si);i+).for( ;isdigit(si);i+).4.1 Basics of Functions4.2 Functions Returning Non-integersExample: convert string to double#include double atof(char s ) double val,power; int i,sign; for(i=0;isspace(si);i+) ; sign=(si=-)?-1:1; if(

15、si=+|si=-) i+; for(val=0.0; isdigit(si); i+) val=10.0*val+(si-0);if(si=.)i+;for(power=1.0;isdigit(si);i+) val=10.0*val+(si-0);power*=10; return sign*val/power;main() double atof(char s ); char s100 double x; scanf(“%s”,s); x=atof(s);printf(“%x=%fn”,x);4.2 Function returning non-integersnote:the type

16、 declared and defined must be consistent.声明的数据类型和定义的数据类型须一致。4.2 Function returning non-integers4.3 External VariablesExternal Variables ( Global ): 外部变量(全局变量)defined outside of the function在函数外部定义的变量称为外部变量。外部变量不属于任何一个函数,其作用域是:从外部变量的定义位置开始,到本文件结束为止。Internal Variables ( Local or Automatic ): 内部变量(局部变量

17、或自动变量)defined inside of the function定义在函数内部,只在函数内起作用,其他函数不能使用4.3 External VariablesInternal Variables (automatic variables)1 The variable defined in main,is accessible only in main.主函数内定义的变量只在主函数中有效The variables which separately defined in different function, can have same name. 不同函数内定义的变量可以有相同的变量名3

18、 Formal variables for function are internal variables. 函数的形参变量是内部变量The variables can be defined in a block. 变量也可以定义在程序块(组)中4.3 External Variables#include main() int a,b; a=3; b=4; printf(main:a=%d,b=%dn,a,b); sub(); printf(main:a=%d,b=%dn,a,b);sub() int a,b; a=6; b=7; printf(sub:a=%d,b=%dn,a,b);运行结果

19、:main:a=3,b=4sub:a=6,b=7main:a=3,b=4运行结果:5 4 3 2 1#include #define N 5main() int i; int aN=1,2,3,4,5; for(i=0;iN/2;i+) int temp; temp=ai; ai=aN-i-1; aN-i-1=temp; for(i=0;iN;i+) printf(%d ,ai);float f1(int a) int b,c; .char f2(int x,int y) int i,j; main() int m,n; .a,b,c有效x,y,i,j有效m,n有效4.3 External V

20、ariablesInternal Variables External Variablesdefined outside of any function (every function is external one) 定义在任何函数之外be accessible by all functions in same source program file 可以被同一文件中的所有函数访问used to data communication between functions, return more values.可用于函数间的数据交换if external variable and intern

21、al variable have same name, then inside of the function, internal variable available,and outside of the function external variable available; 如果外部变量与内部变量同名,则在函数体内,内部变量起作用,函数体外,外部变量起作用4.3 External Variables全局变量是在函数外部定义的,有效范围从定义变量的位置开始到本源文件结束。4.3 External Variables External Variablesint p=1,q=5;float

22、f1(int a) int b,c; .int f3().char c1,c2;char f2(int x,int y) int i,j; main() int m,n; .p,q作用范围c1,c2作用范围 External Variables4.3 External Variables External Variables5.如果在定义点之前的函数想引用该外部变量,则应该在引用之前用关键字extern对该变量作“外部变量声明”。表示该变量是一个已经定义的外部变量。有了此声明,就可以从“声明”处起,合法地使用该外部变量。6. 如果一个程序包含两个文件,在两个文件中都要用到同一个同一个外部变量,

23、需要在任一个文件中定义外部变量,在另一个文件中用“extern”作外部变量声明。7.在定义外部变量时加一个static声明,则这些外部变量只能被本文件使用,而不能被其他文件引用。4.3 External Variables8)为区别局部与全局变量,习惯将全局变量的第一个字母大写;9)设全局变量的作用增加了数据联系的渠道10)应尽量少使用全局变量,因为:全局变量在程序全部执行过程中占用存储单元降低了函数的通用性、可靠性,可移植性降低程序清晰性,容易出错 External Variables4.3 External Variables#include float Max,Min;float ave

24、rage(float array , int n) int i; float sum=array0; Max=Min=array0; for(i=1;iMax) Max=arrayi; else if(arrayiMin) Min=arrayi; sum+=arrayi; return(sum/n);main() int i; float ave,score10; /*Input */ ave=average(score,10); printf(Max=%6.2fnMin=%6.2fn average=%6.2fn,Max,Min,ave);作用域MaxMin例:一个一维数组内放10个学生成绩

25、,写一个函数,求出平均分,最高分和最低分。#include int a=3,b=5; /*a,b为外部变量*/max( int a,int b) /*a,b为局部变量*/ int c; c=ab?a:b; return(c);main() int a=8; /*a为局部变量*/ printf(max=%d,max(a,b);例:外部变量与局部变量同名运行结果:max=8使用extern扩展外部变量的作用域到其他文件例:用extern声明外部变量使用extern扩展文件内外部变量的作用域#include int max( int x,int y) int z; z=xy?x:y; return(

26、z);main() extern A,B; printf(%dn,max(A,B); int A=13,B=-8;运行结果:13int A;#include main() int power(int n); int b=3,c,d,m; printf(enter the number a and its power :n); scanf(%d,%d,&A,&m); c=A*b; printf(%d*%d=%dn,A,b,c); d=power(m); printf(%d*%d=%d,A,m,d);power(int n) int i,y=1; for(i=1;i=n;i+) y*=A; ret

27、urn(y);文件f1.c的内容:int A;#include main() int power(int n); int b=3,c,d,m; printf(enter the number a and its power :n); scanf(%d,%d,&A,&m); c=A*b; printf(%d*%d=%dn,A,b,c); d=power(m); printf(%d*%d=%d,A,m,d);文件f2.c的内容:extern A;power(int n) int i,y=1; for(i=1;i=n;i+) y*=A; return(y);作业 求两个整数的最大公因数和最小公倍数,

28、两个整数从键盘输入。要求用函数调用法。 例:用static声明外部变量文件8-21-f1.c的内容:static int A;main() 文件8-21-f2.c的内容:extern A;power(n) 4.4 Static Variables 静态存储方式: 在程序运行期间分配固定的存储空间。 全局变量全部存在静态存储区,在程序开始执行时给全局变量分 配存储区,程序执行完毕就释放。动态存储方式 动态存储方式则是在程序运行期间根据需要进行动态的分配存储空间。4.3 Static Variables动态存储方式与静态存储方式 从变量存在的时间(生存期)分动态与静态两种存储方式静态存储:程序运行

29、期间分配固定存储空间动态存储:程序运行期间根据需要动态分配存储空间 内存用户区 生存期静态变量: 从程序开始执行到程序结束动态变量:从包含该变量定义的函数开始执行至函数执行结束 具体包含以下四种:auto-自动型 static-静态型extern-外部型 register-寄存器型 程序区静态存储区动态存储区全局变量、局部静态变量形参变量局部动态变量(auto)函数调用现场保护和返回地址等(1) auto int x;(2) static int y;(3) register int i;(4) int z; extern z; 4.3 Static Variablesauto:applied

30、 to an internal variable 自动局部变量(又称自动变量)只在函数内有效,一般缺省。auto int x; int x;函数被调用时分配存储空间,调用结束就释放。在复合语句中定义的自动变量,只在该复合语句中有效;退出复合语句后,也不能再使用,否则将引起错误。4.4 Static Variablesstatic:applied to internal variables, provide private, permanent storage. 静态内部变量在程序执行期间始终存在。4.4 Static VariablesNote1:静态局部变量在编译时赋初值,即只赋初值一次,以

31、后调用函数时不再重新赋值,而只是保留上一次函数调用结束时的值。 4.4 Static VariablesNote2:如果在定义局部变量时不赋初值的话,则对静态局部变量来说,编译时自动赋初值0(对数值型变量)或空字符(对字符变量)。 int x;static int y;系统将其赋值为0或空字符不确定Note3:虽然静态局部变量在函数调用后仍然存在,但是其它函数是不能引用它的。 4.4 Static Variablesadd(int a) int b=0; static int c=3; b+; c+; return (a+b+c);main() int a=2,i; for(i=0;i3;i+

32、)printf(“%dt”, add(a);No.initial valueat the end of callbcbca+b+c103147204158305169#include int fac(int n) int f=1,i; for (i=1;i=n;i+) f=f*i; return(f);main() int i; for(i=1;i=5;i+) printf(%d!=%dn,i,fac(i); #include int fac(int n) static int f=1; f=f*n; return(f);main() int i; for(i=1;i=5;i+) printf

33、(%d!=%dn,i,fac(i); 4.4 Static Variables4.5 Register Variables Register variables (寄存器变量)are to be placed in machine registers, result in smaller and faster programs.register int a;register char c;4.5 Register Variables4.5 Register VariablesExample: 使用寄存器变量int fac(int n) register int i,f=1; for(i=1;i

34、=n;i+) f=f*I; return(f);main() int i; for(i=0;i=5;i+) printf(%d!=%dn,i,fac(i); Note: 只有局部自动内部变量和形式参数才可以声明为寄存器变量。2 few registers can be used.寄存器变量的数量是有限的3 a static variable can not be declared as a register type. 静态变量不能声明为寄存器变量4.5 Register Variables1、求方程 的根。用三个函数分别求3种情况下,解的情况。从主函数输入a,b,c的值。homework4.

35、6 Summarization局部变量外部变量存储类别autoregister局部static外部static外部存储方式动态静态存储区动态区寄存器静态存储区生存期函数调用开始至结束程序整个运行期间作用域定义变量的函数或复合语句内本文件其它文件赋初值每次函数调用时编译时赋初值,只赋一次未赋初值不确定自动赋初值0或空字符局部变量默认为auto型局部static变量具有全局寿命和局部可见性局部static变量具有可继承性extern不是变量定义,可扩展外部变量作用域4.6 Summarization4.7 Header FilesHeader file means one file include

36、 other file overall.文件包含是指,一个源文件可以将另一个源文件的全部内容包含进来。syntax:#include “filename” or#include 两种格式的区别仅在于:(1)使用尖括号:系统直接到存放C库函数头文件所在的目录中去查找要包含的文件,这称为标准方式。(2)使用双引号:系统首先到当前目录下查找被包含文件,如果没找到,再按标准方式查找。4.7 Header Files#include “file2” file1.cABfile2.cBAfile1.c4.7 Header FilesNote:1.在编译中,将“包含”以后file1.c作为一个源文件单位进行

37、编译。4.7 Header FilesNote:2.一个include命令只能指定一个被包含文件,若有多个文件要包含,则 需用多个include命令。3. 文件包含允许嵌套,即在一个被包含的文件中又可以包含另一个文件。#include “file2” file1.cABfile2.cBAfile1.c4.如果file2.h中有全局变量,它也在file1.h中有效,不必用extern声明。例 文件包含举例/* powers.h */#define sqr(x) (x)*(x)#define cube(x) (x)*(x)*(x)#define quad(x) (x)*(x)*(x)*(x)#in

38、clude #include powers.h#define MAX_POWER 10void main() int n; printf(numbert exp2t exp3t exp4n); printf(-t-t-t-n); for(n=1;n=MAX_POWER;n+) printf(%2dt %3dt %4dt %5dn,n,sqr(n),cube(n),quad(n);#include int max(int x, int y) return (xy)?x:y;int min(int x, int y)return (xy)? y:x;void printstar()printf(“

39、*”);calc.h#include #include “calc.h”main( ) int a,b,c,d;. c=max(a,b);. d=min(a,b);. printf(%d,%d”,c,d);work.c例 文件包含举例如何运行一个多文件的程序用Turbo C 环境实现多文件程序的运行先输入并编辑各个源文件分别存盘建立一个“项目文件” ,只包括组成程序的所有文件名。将此文件以“ *.prj”存盘在主菜单中选择Project菜单,选择菜单项Project name ,输入刚建立的项目文件名按+运行。用#include 命令实现多文件程序的运行格式:#include “源程序文件名”

40、如果与当前文件不在同文件夹中,还需适当指明路径,如: #include “d:abcf1.c”此时各文件中的函数被当作在同一文件中,main函数中原有的extern声明可以不要。如何运行一个多文件的程序4.8 Block Structure variable can be defined in a block-structured fashion within a function 程序组-复合语句if(n0) int i; /* a new variable i, and its scope only inside the block*/ for(i=0;in;i+) .4.8 Block

41、Structuremain() int i=1,j=4; int i=2; int i=3; printf(“i=%d,j=%dn”,i,j); printf(“i=%dn”,i); printf(“i=%dn”,i); 4.8 Block StructureOutput:i=3,j=4i=2i=1Note1:程序组中定义的变量可以隐藏在该程序组外面定义的同名变量。 4.8 Block StructureNote2:程序组中定义的自动变量每当进入该程序组时就被初始化,静态变量只在第一次进入该程序组时初始化。 4.9 Initialization In the absence of explic

42、it initialization(在进行赋值之前) external and static variables are guaranteed to be zero(0); 外部变量和静态变量自动赋予0 automatic and register variables have undefined initial value.自动部变量和寄存器变量的初始值不确定4.9 InitializationFor external and static variables the initializer must be a constant expression;the initialization i

43、s done once; 初始化为常量表达式,其只有一次初始化For automatic and register variables1 the initializer may be any expression involving previously defined values, even function call;2 the initialization is done each time the function or block is entered; 初始化为任意表达式,甚至是函数调用,每次进入函数时均进行初始化的工作。4.9 Initializationint day =31

44、,28,31,30,31,30,31,31,30,31,30,31;Declaration with a list of initializer enclosed in braces and separated by commas. 数组元素对应的数值包括在花括号,依次对应,并用逗号分割。when the size of array is omitted, the complier will compute the length by counting the initializers; if there are fewer initializers for an array than the

45、 number specified, the missing elements will be day12=31, 28;如果只有部分数组元素被赋值,其他元素初始化为04.9 Initialization char s=“could”;instead of char s=c,o, u, l, d, 0;Note: The size of array is six (five characters plus 0)4.9 Initialization4.9 Initializationint a5=0,1,2,3,4 a0=0;a1=1;a2=2;a3=3;a4=4;int a5

46、=0,1,2 int a5=0,1,2,0,0 int a =0,1,2,3,4 int a5=0,1,2,3,4int a5=0,1,2,3,4,5,6 4.10 Recursion A function call itself either directly or indirectly.函数直接或间接的调用自身4.10 RecursionExample: printf a number as a character string#include void printd(int n) char s; int i=0; if(n=0;i-)putchar(si);n=-1234.10 Recu

47、rsion转换成字符串逆序Example: printf a number as a character string#include void printd(int n) if(n1)4.10 Recursion结束条件n0;n=0或者n=1;n! =Recursion ordern! (n-1)! (n-2)! 2! 1! Return order 用递归的方法求n!long fac(int n) long f; if(n0) printf(“n0,data error”); else if (n=0|n=1) f=1; else f=fac(n-1)*n; return(f);main(

48、) int n; long y; scanf(“%d”,&n); y=fac(n); printf(“%d!=%10ld”,n,y);4.10 RecursionRecursion order 5! 4! 3! 2! 1! Recursion order 5! 4! 3! 2! 1!120 24 6 2 1 Return order homework有一对兔子,从出生后第3个月起每个月都生一对兔子。小兔子长到第3个月每个月又生一对兔子。假设所有兔子不死,求第n个月的兔子总数是多少?(Fibonacci数列)要求:用递归法;n可以由用户设置。4.11 The C Preprocessor C p

49、rovides three kinds of preprocessor.file inclusion (#include)to include the contents of a file during compilation Macro substitution (#define)to replace a token by an arbitrary sequence of characters用一个字符串替代指定的标示符Conditional inclusion4.11 The C Preprocessor #include “filename”#include Any source lin

50、e of following form is replaced by the contents of the file filename,4.11 The C Preprocessor 4.11.1 file inclusion4.11 The C Preprocessor 4.11.2 Macro SubstitutionMacro substitution without argumentsMacro substitution without arguments #define PI 3.1415926#define FOREVER for(;)#define INPUT “please input datas:n”4.11 The C Preprocessor 4.11.2 Macro SubstitutionMacros without arguments#define name replacem

温馨提示

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

评论

0/150

提交评论