c语言的static属性

来源:互联网 发布:龙腾世纪审判优化 编辑:程序博客网 时间:2024/06/11 21:19

 一说到C的static属性首先想到隐藏,对于static变量值仅函数体内可见,对于static函数来说只有当前文件可见。对于变量,除了隐藏,static还有下面两个作用:保持变量内容的持久;默认初始化为0。存储在静态数据区的变量会在程序刚开始运行时就完成初始化,也是唯一的一次初始化。下面看个简单的测试程序

#include <stdio.h>
#define test_num 3
void test_static()
{
    static int s = 0;//只初始化一次,可以调试看看变量的变化

    printf("static variable %d\n", s);

    ++s;
}
int main()
{
 int s = -1;
 for(int i = 0; i < test_num; ++i)
 {
     test_static();
 }
 printf("variable s = %d\n", s);//test_static里的s变量不可见
return 0;
}

打印结果:0 1 2-1说明量内容的持久!