C's Static Keyword
After this post you shouldn't find the static keyword confusing in C anymore! Let's get started...
The first context we find static variables is in functions. First, it's important to understand that there are two types of "storage classes" in C. The first is auto, short for automatic, which is the default if no storage class is specified. This means that a variable is automatically destroyed upon exit from the code block inside a function or function itself that it's defined in. The other storage class in a function is static. This means that a variable maintains the static memory allocation that is defined in it's first execution through the respective line of code. This static variable stays around until program termination. It doesn't even get reinitialized on a second pass through it's respective line of code, so it's great for counts and other things internal to the function that shouldn't be divulged to the outside world.
At this point you may be wondering about static variables in a global scope or, put another way, at the file level. Either these static variables would be in a header or implementation file. In the implementation file, they wouldn't be visible to clients of the implementation because they would only have access to the header file, in the first place. In the header file, that is included in other files, the static variable definations would also be included, and since included they would be statically visible to their respective header file and all files that use that header. Like static variables, global variables at the file level, retain their values from program execution to termination. Thus, there is absolutely no reason to make global variables static.
In the second context, we find static functions. Say we want to include a private function in a header for consistancy and completness. By doing this, we would normally make the function public to everything else that includes its respective header file. However, if we prepend the function prototype and definition with the static keyword we can still keep it private as originally intended. Now you may be thinking, "Wait just a minute, Samuel! In the previous paragraph, you stated that static variables at the global scope were still public thanks to being able to include them, along with the rest of their header, in the same code that wouldn't be able to access static functions in the same included header file. Pardon me, but this seems a bit inconsistent!" It is and that's all there is to know about the static keyword in C.

No comments:
Post a Comment