关于C语言中static保留字的使用

 static存储类型可以用于全部变量,无需考虑变量声明的位置。但是作用于块外部和块内部时具有不同的作用。

(1)当作用于函数内部时,和每次程序离开所在块就会丢失值的自动变量不同,static变量会保存下去,块内的static变量只会在程序执行前进行一次初始化,而自动变量则会每次都初始化。接下来对此特性进行验证。

#include "stdio.h"
void test(void)
{
static int a = 10;
int b = 10;
printf("a = %d,b = %d\n",a,b);
a = 20;
b = 20;
printf("a = %d,b = %d\n",a,b);
a = 30;
b = 30;
printf("a = %d,b = %d\n",a,b);
printf("***************\n");
}
void main()
{
test();
test();
}

test()函数中初始化了两个变量,static变量a和自动变量b,第一次调用完成后结果都是一样的,但是在完成第二次的调用以后,不同的结果出现了,a=30,这就是在上次调用完成之后初始化的30,退出函数后并不会丢失,再次调用函数时也不会初始化,只有在赋值的时候才会改变。

(2)当作用于函数头时。此时的函数只在当前文件有效,对于其他文件不可见。验证程序如下:

test.c

/*test.c*/
#include "test.h"
#include "stdio.h"
static int a = 10;
static void test_a()
{
  printf("a = %d\n",a);
}
void put()
{
    test_a();
}

test.h

/*test.h*/
#ifndef __TEST_H__
#define __TEST_H__
void put();
static void test_a();
#endif

main.c

#include "stdio.h"
#include "test.h"
void main()
{
  put();
  test_a();
}

运行之后发生了如下的错误:
1>c:\users\administrator\desktop\20171212\2017121201\2017121201\main.c(9): error C2129: 静态函数“void test_a()”已声明但未定义
1> c:\users\administrator\desktop\20171212\2017121201\2017121201\test.h(6) : 参见“test_a”的声明
由此可见,static在函数头上时只能在当前文件有效。

猜你喜欢

转载自www.linuxidc.com/Linux/2017-12/149395.htm
今日推荐