第8章函数--C语言程序设计(谭浩强第三版).pptVIP

  • 12
  • 0
  • 约2.43万字
  • 约 77页
  • 2017-07-03 发布于湖北
  • 举报

第8章函数--C语言程序设计(谭浩强第三版).ppt

第8章函数--C语言程序设计(谭浩强第三版)剖析

int p=1,q=5; float f1(int a) { int b,c; ……. } int f3() {….. } char c1,c2; char f2(int x,int y) { int i,j; …… } main() { int m,n; ……. } c1,c2的作用范围 p,q的作用范围 extern char c1,c2; extern char c1,c2; c1,c2 的作用范围 扩展后 c1,c2 的作用范围 扩展后 extern对全局变量作用域的扩展 1. 在一个文件内引用定义在后面的外部变量需extern声明 例:教材8.20 用extern声明外部变量,扩展它在程序文件中的作用域。 #include stdio.h void main() { int max(int,int); extern A,B; /*外部变量声明*/ printf(%d\n,max(A,B)); } int A=13,B=-8; /*定义外部变量*/ int max(int x,int y) /*定义max函数 */ { int z; z=xy?x:y; return(z); } 2. 在多文件的程序中,引用其它文件中的外部变量需extern声明 例 int global; extern float x; main() { int local; . . . } extern int global; static int number; func2() { . . . } float x; static int number; func3() { extern int global; . . . } file1.c file2.c file3.c 用extern将外部变量的作用域扩展到其他文件。 例:教材8.21,输出a × b和a的m次方 file1.c int a; 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=%d\n,a,b,c); d=power(m); printf(%d**%d=%d,a,m,d); } file2.c extern int a; int power(int n) { int i,y=1; for(i=1;i=n;i++) y*=a; return(y); } 文件file2.c中extern a;声明在本文件中出现的变量a为一个已经在别的文件中定义的外部变量,本文件将不再为它分配内存。本来a的作用域为file1.c,现在用extern A将它作用域扩大到file2.c 3. 用static将外部变量的作用域限制在本文件中 在程序设计中,某些外部变量只限于被本文件引用,而不能被其他文件引用。这时可以在定义外部变量时加一个static声明。 file1.c static int a; void main ( ) { … } file2.c extern int a; void fun (int n) { a=a*n; } ×,无法引用file1.c中的a变量 例如: 变量存储类型 静态 动态 存储方式 程序整个运行期间 函数调用开始至结束 生存期 编译时赋初值,只赋一次 每次函数调用时 赋初值 自动赋初值0或空字符 不确定 未赋初值 静态存储区 动态区 存储区 寄存器 局部变量 外部变量 作用域 定义变量的函数或复合语句内 本文件 其它文件 register 局部static auto 外部static 外部 存储类别 局部变量默认为auto型 register型变量个数受限,且不能为long, double, float型 局部static变量具有全局寿命和局部可见性 局部static变量具有可继承性 extern不是变量定义,可扩展外部变量作用域 归纳:变量的属性 数据类型:变量是对程序中数据的存储空间的抽象(操作属性) 存储属性 存储器类型:寄存器、静态存储区、动态存储区 作用域:变量在某范围内有效-------局部变量与全

文档评论(0)

1亿VIP精品文档

相关文档