“静态”变量有两种不同的作用。如果你将一个变量声明为静态within函数,那么即使在函数返回后,在函数内分配给它的内存仍然可以访问,例如:
#include <stdio.h>
char *func1()
{
static char hello[] = {"Hello, world!\0"};
return hello;
}
char *func2()
{
char goodbye[] = {"Goodbye!\0"};
return goodbye;
}
int main( int charc, char *argv[] )
{
printf( "%s\n", func1() );
printf( "%s\n", func2() );
}
对 func1() 的调用是有效的,因为在函数内部声明的变量“hello”被设置为静态,所以即使在函数返回后它仍然可以访问。
对 func2() 的调用是未定义的行为,因为一旦函数返回分配给“再见”的内存,就会返回给操作系统。一般会出现段错误,程序会崩溃。
“静态”会做的另一件事是,当变量(或函数)在文件级别声明为静态时,该变量(或函数)将只能在该文件中访问。这是为了数据封装。
所以如果我有 file1.c 和以下代码:
static *char hello()
{
static char hi[] = {"Hi!\0"};
return hi;
}
然后在 file2.c 我有:
#include <stdio.h>
extern char *hello(); //This lets the compiler know that I'm accessing a function hello() in another file
int main( int charc, char *argv[] )
{
printf( "%s", hello() );
return 0;
}
如果我编译它
gcc file1.c file2.c -o test
编译器会抱怨找不到 hello()。