The static storage class is related to the linkage and storage of an object. It doesn't really have anything to do with the type of the object.
Below is an explanation of what (I think) your program is doing:
enum day {sun=1,mon,tue,wed,thur,fri,sat};
This declares an enumerated type with the tag name day
, and also defines a number of enumeration constants and their values.
static enum direction {UP,DOWN,RIGHT,LEFT};
This declares an enumerated type with the tag name direction
, and also defines a number of enumeration constants and their values.
The static
storage-class is meaningless here, because you are not defining (allocating storage) for an object.
int static_enum()
{
static enum direction dir = UP;
printf("dir = %d\n",dir);
dir++;
}
This defines a block-scope object named dir
of type enum direction
. The static
storage-class means that the object will be allocated and initialized at program startup, and that it will retain its last stored value between function calls.
int main()
{
printf("\nsun = %d mon = %d tue = %d wed = %d thurs = %d fri = %d sat = %d\n",sun,mon,tue,wed,thur,fri,sat);
This will output the values of the enumeration constants.
enum day fri = 25;
This defines a block-scope object named fri
of type enum day
, initialized with the value 25
. The enumeration constant also named fri
will not be visible anymore within this block (unless you re-declare enum day
).
// now friday gets modified from 21 to 25 becasue we have re-assigned the value
printf("\nfri = %d\n",fri);
This outputs the value of the object fri
, not the value of the enumeration constant fri
. Nothing has been modified.
// now saturday will still have value 22
printf("\nsat = %d\n",sat);
This outputs the value of the enumeration constant sat
, as expected.
printf("\n");
static_enum();
static_enum();
return 0;
}
One might wonder why the language allows the static
storage-class in a declaration that does not define (allocate storage for) an object. I think this is just a syntactical convenience due to the way that declarations and definitions share the same syntax. The C syntax allows you to pile any number of storage-class, type-specifier, type-qualifier, function-specifier and alignment-specifier in any order in a declaration. However, many combinations are disallowed or cause undefined behavior according to various semantic sections of the C standard. I don't think there is anything that prohibits the meaningless static
keyword in the declaration of direction
.