浅谈static关键字<1>


     static可以说一直伴随着我们的编程生涯,对于他的用途和好处一言难尽,实在太多了,对于初学者很容易被static搞的晕头晕脑,即便是懂点了也是记一些概念性的东西,今天我通过代码让你对static有更深一步的了解.
      今天我们主要分析一下在C语言中static,OK,从变量说起
1.static局部变量
        定义一个局部变量那么他的生命周期肯定是当前函数的结束,但是被static修饰的后之后,他的声明周期就扩展为整个程序的结束,并且存储在全局区,那么他是不是已经变成全局变量了呢?
#include <stdio.h>
int func(int r)
{
static int n=10;
return r*n;
}
int main(int argc,char* argv[])
{
printf("%d\n",func(10));
printf("n=%d\n",n);
return 0;
}
发现:error C2065: 'n' : undeclared identifier说n未定义说明他没有编程全局变量
所以:
static修饰的局部变量他的生命周期增长到整个程序的结束,但是他的作用域没有变,仍然是自己所在的函数作用返回内。
2.static全局变量
假如说我们现在有三个文件:test.h test.c main.c
test.h:放了一些函数或者全局变量的声明
test.c:将test.h头文件加入,并把test.h中声明的函数或者变量定义
main.c:使用test.h中的变量或者函数
不用static修饰代码如下:
test.h:#define _TEST_H
#define _TEST_H
extern int g_global;
#endif
test.c:
#include "test.h"
int g_global=100;
main.c:
#include <stdio.h>
#include "test.h"
int main()
{
printf("%d\n",g_global);
}
gcc main.c test.c发现程序没有任何问题,输出结果为100
当然我们讲的是static,加上static试一试吧
test.h:#define _TEST_H
#define _TEST_H
extern static int g_global;
#endif
test.c:
#include "test.h"
static int g_global=100;
main.c:
#include <stdio.h>
#include "test.h"
int main()
{
printf("%d\n",g_global);
}
发现竟然可以访问,但是结果为0
不是说static的全局变量只能在定义他的文件中访问吗,但是为什么咱们现在在main中也访问了,
但是再换一种方法写一写:
test.h:#define _TEST_H
#define _TEST_H
extern int g_global;
void print();
#endif
test.c:
#include "test.h"
int g_global=100;
static int g_static=123;
void print()
{
printf("g_static=%d\n",g_static);
}
main.c:
#include <stdio.h>
#include "test.h"
int main()
{
printf("%d\n",g_static);
print();
}
出现错误了,说明那句话说的也不是不对
好了,结论:
static修饰的全局变量,生命周期在整个项目的结束,但是这个全局变量的访问作用域仅限于定义他的那个文件中。如果在头文件中声明这个static全局变量了,那么在main函数中他进行了宏替换,认为声明了这个static变量并没有进行初始化,所以输出他的值是0,第二种方法在宏替换后没有声明语句,所以他就出现错误了。
3.static函数
        如果不加static声明的函数,在别的文件中直接加入了他的声明都是可以调用的,但是如果加了static,那么这个静态函数的作用域就只限于定义他的那个文件了。和静态全局变量相似。
 
 
 
 
 
 

相关内容

    暂无相关文章

评论关闭