您的位置:首页 > 其它

static作用

2016-06-24 17:18 183 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: