C语言59课变量生存周期

第59课变量生存期

·变量的存储类型
·auto 自动存储 只用于块作用域的变量声明中,局部变量默认情况下归为自动存储类型
·register(register int)寄存器存储 只用于块作用域的变量,请求速度快,对于循环次数较多的循环控制变量及循环体内反复使用的变量均可定义为寄存器变量。
·static 静态存储 载入程序时创建对象,程序结束对象小时
·extern 外部变量 说明符表示声明的变量定义在别处。作用域是整个程序,生存期贯穿应用程序的开始和结束。

·实例:计算某个函数被调用了多少次(static使用)
·codeblock–>file–>new–>file–?C/C++ source(函数可以写到另一个文件中去)

		
			//程序*****************************************************
			#include <stdio.h>
			#include <stdlib.h>
			
			int main()
			{
				int count = 0;
				counter();
				counter();
				counter();
				count = counter();//第四次调用
				printf("count = %d\n",count);
				return 0;
			}
			
			------------------------------------------------------------submain
			/**
			*MyCount.c
			*用来存放计算函数调用次数的函数原型及实现
			*/
			
			void count();   //用来计算本函数被调用了多少次
			
			void counter()
			{
				//静态存储不销毁
				static int count = 0;//第一次执行会分配空间,以后就不再分配空间了。
				count++;
				return count;
			}
			
			
	
			//运行结果*****************************************
			count = 4
			
			Process returned 0 (0x0)   execution time : 1.285 s
			Press any key to continue.
			//运行结果*****************************************	
			
·实例:计算某个函数被调用了多少次(extern int 使用)


			//程序*****************************************************
			#include <stdio.h>
			#include <stdlib.h>
			int whileCount = 0; //全局变量,用来记while循环执行的轮数
			//全局变量的作用域是当前源文件!!!在另一个.c里面整个全局变量不起作用的!
			//若要使用,需要定义外部变量extern
			
			int main()
			{
				int value;      //自动变量-执行循环的次数
				register int i; //将循环变量设置为寄存器存储模式
				printf("请输入循环执行的次数(按0退出):\n");
				//用户输入的value为整型数字并且值大于0时,进入循环
				while(scanf("%d",&value) == 1 && value > 0)//实现一个循环录入效果
				{
					whileCount++;
					for(i = value; i >= 0; i--)// for 循环被调用了value+1次
					{
						//1、我们想知道循环执行了多少次
						//2、我们还想知道,counter函数被调用了多少次
						counter(i);//每次循环调用counter函数
					}
				}
				return 0;
			
			}
			//程序*****************************************************

			//sub程序*****************************************************

			/**
			*MyCount.c
			*用来存放计算函数调用次数的函数原型及实现
			*/
			
			extern int whileCount;//引用了外部变量
			
			void count(int);   //用来计算本函数被调用了多少次
			
			void counter(int i) //传了一个值进来
			{
				//静态存储不销毁
				static int subTotal = 0;//第一次执行会分配空间,以后就不再分配空间了。
				subTotal++;
				printf("counter函数被调用了%d次\n",subTotal);
				printf("当前是第%dwhile\n",subTotal);
				return 0;
			}
			//sub程序*****************************************************
			

			
·总结
		·全局变量,本文件内有效,其他文件想要调用必须定义	extern int
		·static int 不会销毁,一次分配空间,之后就一直是这个空间

猜你喜欢

转载自blog.csdn.net/cxd15194119481/article/details/85847962