static改变了变量的作用域,在全局变量中使用时,会锁定该全局变量,使其只能在自己所在的源文件使用。

如下,若不加static,全局变量在不同源文件间可通用。

int a = 2
(first.c)
int main()
{
printf("%d\n",a);
}(second.c)

如下,如果加static,全局变量便不可通用

static int a = 2
(first.c)
int main()
{
printf("%d\n",a);
}(second.c)

而在局部变量中,static使局部变量的生命周期变长。

即在使用完一次局部变量后不进行销毁。

如不加static,结果输出五个a=2

void test()
{
int a = 1;
a++;
printf("a=%d\n",a);
}

int main()
{
int i = 0;
while (i<5)
{
test();
i++;
}
else
return 0;
}

如加static,结果输出a=2到6

void test()
{
static int a = 1;
a++;
printf("a=%d\n",a);
}

int main()
{
int i = 0;
while (i<5)
{
test();
i++;
}
else
return 0;
}