Quote:
Originally Posted by brianafischer
I am trying to create a list of "good" programming practices for the students. I cannot seem to google a good reason for proper use of static variables instead of globals. Anyone interested in sharing some knowledge?
When is a static variable required over a global?
What are the advantages of static variables?
What are the disadvantages of static variables?
Thanks!
|
Two properties of variables in C are persistence and scope or visibility. Globals and statics are persistent since they hold their values for the duration of program execution as opposed to automatic variables which become invalid when the execution of the program exits the scope where the automatic is defined. Variables allocated on the heap persist between the malloc (or similar) and free calls.
Global variables have program scope meaning they can be seen anywhere in the entire program provided a declaration is visible. Static variables can have file, function, or even block scope. Automatic variables can only have function and block scope by contrast. The visibility of heap variables is controlled by the visibility of the pointer variables which, well, point to them.
Good programming practices usually suggest that variables be given the
smallest scope to do the job. This prevents accidental access via things like mispelling the variable name. It also limits name clashes for commonly used variable names and makes the logic easier to follow. That said, most programmers don't use block scope in C and the smallest common scope is the function. Using more descriptive names helps with name clashes but it's nice to be able to use a simple descriptive name without having to worry too much about it until the linker complains. Some coding styles preface global variables with "g_" and file scope statics with "s_" to help with clashes and to make it more obvious what the variable really is.
With microcontrollers like the PIC which have limited variable space and especially limited stack space, it can be more efficient to use statics or grobals to more efficiently use memory. Also, from a speed standpoint, some microcontrollers can access static memory faster than a stack variable (I'm not sure about the PIC in this respect). Memory management with a microcontroller can take more understanding than for your typical PC program.