Static variables are usually: (in most programming languages) shared, persistent, and allocated on the code section of the program
But what does that have anything to do with the word static? What is so static about that? I thought static
means doesn't change?
For example, in vb.net static is written shared and that means a member function that can be accessed without object instantiation. Static within function usually means that the variable life time is the life time of the whole program. It seems that static variables are stored on the code section of the computer. Am I correct in my understanding based on the example?
Well, I think the keyword is appropriate. It means the variable you declare as static will remain stored at the same location throughout the whole execution of your program.
I thought static means doesn't change
This corresponds to the const
keyword. Const implies it doesn't change, static implies it doesn't "move", as to it stays stored at the same location.
In general, what doesn't change with something that is static in a programming language is whether it is alive or not. Static variables are always alive; they have a single instance which comes into being either at the beginning of the program or the first time they are visible, and lasts until the end of the program. Non-static variables come and go, as blocks are entered and left, or as class instances are created and destroyed.
In C++, for reasons of C compatibility, static, when applied to
variables at namespace scope, has a completely unrelated
meaning: it means that the variable has internal, rather than
external linkage, and is not visible in other translation units.
Why the word static was adopted for this in early C, I don't
know; I can only guess that they needed something, and didn't
want to introduce a new keyword. (Originally, in the very
earliest versions of C, variables at file scope obeyed the rules
of a Fortran named common block: all variables of the same name
referred to the same storage.) Looking back, of course (with 20/20
hindsight), the default for variables at file scope should have
been internal linkage, with a special keyword (public
?) to say
that the variable had external linkage. But this was a lot less
obvious in the early 1970's.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With