The keyword static
has many meanings that depend on the context where the keyword is used.
If the array of the structure is declared inside a function then it means that the array has the static storage duration instead of the automatic storage duration.
Consider the following example
#include <stdio.h>
struct A
{
int x;
};
struct A * f( void )
{
struct A a = { 10 };
return &a;
}
int main( void )
{
struct A *pa = f();
printf( "pa->x = " );
printf( "%d\n", pa->x );
}
Here function f
defines an object of type struct A
with the automatic storage duration and returns pointer to this object. As the object will not alive after exiting the function then the program has undefined behaviour. For example running this program using an inline compiler I got the following result
pa->x = 1073981248
On the other hand if within the function the object will have the static storage duration then the program will be well-formed because the object willl be alive after exiting the function
#include <stdio.h>
struct A
{
int x;
};
struct A * f( void )
{
static struct A a = { 10 };
return &a;
}
int main( void )
{
struct A *pa = f();
printf( "pa->x = " );
printf( "%d\n", pa->x );
}
The program output will be as expected
pa->x = 10
The object will keep its value between calls of the function. For example
#include <stdio.h>
struct A
{
int x;
};
struct A * f( void )
{
static struct A a = { 10 };
return &a;
}
int main( void )
{
struct A *pa = f();
printf( "pa->x = " );
printf( "%d\n", pa->x );
pa->x = 20;
pa = f();
printf( "pa->x = " );
printf( "%d\n", pa->x );
}
The program output is
pa->x = 10
pa->x = 20
If the array of the structure is declared outside any function then it means that (apart from the static storage duration by default) the array name has internal linkage that is it is invisible outside the compilation unit where it is declared.
If several compilation units include the same declaration of the array with keyword static then each compilation unit has its own separate instance of the array.