What is the use of Static local variable when we can get a global variable at the same cost?

Adi picture Adi · Apr 4, 2013 · Viewed 28.4k times · Source

In C ,what is the use of static storage class when an external variable can serve its purpose at the same cost ie. both occupy storage space in the data segment of the executable.

I have much better scope with external variable.If i want the scope of external variable to be specific file i do not declare this variable else where.i see a lot of flexibility with a global variable that static local variable

And we can refer to local static variable outside the function if we have the address of the variable.Memory for local static variable will be in Data segment not in the stack frame of the function.So unique feature does static storage class bring to the table.

I just want to know whether static has any subtle purpose that i m not aware of.

Answer

Eric Postpischil picture Eric Postpischil · Apr 4, 2013

You write that a global variable has a “better” scope. This is incorrect. It has a bigger scope. Bigger is not better.

Bigger may be necessary, if you need an identifier to be visible in more places, but this is often not the case. But a bigger scope means more exposure to errors. Global variables muddle the semantics of routines by making it harder to see what program state they use and change, and it increases the probability of errors caused by failing to declare a local identifier and of other errors.

In particular, an identifier with external linkage will collide with identifiers in other libraries. Consider what happens when you are writing a physics application, have an external identifier named acceleration, and link with a physics library that also has an external identifier named acceleration. The program will fail. Because of this, external identifiers are usually bad design.

A significant limit on our ability to develop and maintain complex software is human error. Much of programming language semantics limits the language to prevent errors. With a raw computer, you can add two pointers, trash your stack pointer, accidentally load the bytes of a float into an integer register, and so on. Good programming languages make these errors difficult to do by mistake.

Global variables were a larger source of errors before scoping rules helped control them. Good programmers limit the scopes of their identifiers.