static作用

1>隐藏:
    如果加了static,就会对其他源文件隐藏。利用这一特性可以在不同的文件中定义同名函数和同名变量,而不必担心命名冲突。
    静态局部变量只能被其作用域内的变量或函数访问。也就是说虽然它会在程序的整个生命周期中存在,由于它是static的,它不能被其他的函数和源文件访问


2>static变量还有两个特性:
   1.保持变量内容的持久,只能初始化一次。存储在静态数据区的变量在程序刚开始运行就完成初始化,static变量初始值一定要是常量。
       共有两种变量存储在静态存储区:全局变量和static变量,只不过和全局变量比起来,static可以控制变量的可见范围。
   2.默认初始化为0.在静态数据区,内存中所有的字节默认值都是0x00.
   

   总结:static主要功能是隐藏,其次是因为static变量存放在静态存储区,所以具备持久性和默认值0.


#include <stdio.h>
   
   int fun(void)
   {
        static int count = 10;//实际赋值没有执行过
   	return count--;
   }
   
   int count = 1;
   
   int main(void)
   {
   	printf("global\t\tlocal static\n");
   	for(; count <= 10; ++count)
   	{
   	<span style="white-space:pre">	</span>printf("%d\t\t%d\n", count, fun());
   	}
   		
   	return 0;
   }


[gfj@kfjk2 c]$ ./a.out
global          local static
1               10
2               9
3               8
4               7
5               6
6               5
7               4
8               3
9               2
10              1


//static变量初始值一定要是常量  


#include <stdio.h>

int main()
{
  while(1)
  {
    int b = 2;
    static int a = 5 + b ;
    printf("a= %d\n",a);
    sleep(2);
  }
}

[gfj@kfjk2 c]$ gcc test.c
test.c: In function ‘main’:
test.c:9: error: initializer element is not constant   


#include <stdio.h>

int main()
{
  while(1)
  {
    static int a = 5;//<span style="font-family: Arial, Helvetica, sans-serif;">只能初始化一次,所以只执行了一次</span>
    a = a + 1;
    printf("a= %d\n",a);
    sleep(2);
  }
}

[gfj@kfjk2 c]$ ./a.out
a= 6
a= 7
a= 8
a= 9
a= 10
a= 11
a= 12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值