Sunday 20 November 2011

Why should I use static variables? in C programming

Why should I use static variables?

Static variables are excellent for use as a local variable that does not lose its value when the function exits. For example, you might have a function that gets called numerous times, and that part of the function’s job is to count how many times it gets called. You cannot accomplish this task with a simple local variable becauseit will be uninitialized each time the function is entered. If you declare your counter variable as static, its current value will be maintained, just as with a global variable.

So why not just use a global variable instead? You could, and there’s nothing wrong with using a global variable. The problem with using global variables is that maintaining a program with lots of global variables becomes cumbersome, particularly if you have numerous functions that uniquely access one global variable. Again, there’s nothing wrong with doing it that way—the issue simply becomes one of good code design and readability. By declaring such variables as static, you are informing yourself (or another person who might be reading your code) that this variable is local but is treated like a global (maintains its value). If the staticvariable was instead declared as a global, the person reading the code must assume that the global is accessed

in many places when in fact it might not be.In summary, the reason you should use static variables is that it is good programming practice when you need a localized variable that maintains its state.

Cross Reference:

II.17: Can static variables be declared in a header file?

No comments:

Post a Comment