There's two different things that 'static' variables do. If you declare a variable as static within a function, then the memory allocated to it within the function remains accessible even after the function returns, example:
#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() );
}
The call to func1() is valid, as the variable "hello" declared inside the function was set as static, so it remains accessible even after the function returns.
The call to func2() is undefined behavior as once the function returns the memory allocated to "goodbye" is returned to the operating system. Generally, you will get a segmentation fault and the program will crash.
The other thing 'static' will do is when a variable (or function) is declared as static at the file level, that variable (or function) will only be accessible within that file. This is for data encapsulation.
So if I have file1.c with the following code:
static *char hello()
{
static char hi[] = {"Hi!\0"};
return hi;
}
And then in file2.c I have:
#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;
}
If I compile it with
gcc file1.c file2.c -o test
The compiler will complain that it can't find hello().