zoukankan      html  css  js  c++  java
  • 静态变量

    静态变量(static variable)

    我们可以创建具有 块作用域、无链接、静态存储期 的局部静态变量。其与局部自动变量一样,具有相同的作用域,但是程序在离开它们所在函数后,静态变量不会消失,在多次函数调用之间会记录它们的值。

    #include <stdio.h>
    
    void TryStat(void);
    
    int main()
    {
    	for (int i = 1; i <= 3; i++)
    	{
    		printf("Here comes iteration %d:\n", i);
    		TryStat();
    	}
    	
    	return 0;
    }
    
    void TryStat(void)
    {
    	int fade = 1;
    	static int stay = 1;	// 逐步调试程序时,会发现程序跳过了这句声明
    	
    	printf("fade = %d and stay = %d\n", fade++, stay++);
    }
    

    该程序的输出如下:

    Here comes iteration 1:
    fade = 1 and stay = 1
    Here comes iteration 2:
    fade = 1 and stay = 2
    Here comes iteration 3:
    fade = 1 and stay = 3
    

    静态变量 stay 保存了它被递增1后的值,但是 fade 变量每次都是1。这表明了初始化的不同:每次调用 TryStat() 都会初始化 fade ,但是 stay 只在编译 TryStat() 时被初始化一次。如果未显式初始化静态变量,它会被初始化为 0。

    不能在函数的形参中使用 static :

    int wontwork(static int flu);		// 不允许
    

    Tip
    逐步调试时,程序之所以会跳过第19行的声明: “static int stay = 1; ”,是因为静态变量和外部变量在程序被载入内存时已加载完毕。把这条声明放在 TryStat(void) 函数中是为了告诉编译器只有 TryStat(void) 函数才能看到该静态变量。这条声明并未在运行时执行。

  • 相关阅读:
    pip install uwsgi 报错 AttributeError: module 'os' has no attribute 'uname'
    npm安装vue
    Node.js安装及环境配置之Windows篇
    Centos7 安装nodejs
    Centos7 Jenkins 插件下载速度慢、安装失败
    Centos7 使用docker 安装redis
    Centos7 安装jdk
    supervisor配置文件详解
    MySQL5.7 group by新特性,报错1055
    配置python虚拟环境Virtualenv及pyenv
  • 原文地址:https://www.cnblogs.com/ltimaginea/p/13587249.html
Copyright © 2011-2022 走看看