Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does static variable in general mean for various programming language and circumstances?

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?

like image 909
user4951 Avatar asked Feb 15 '13 10:02

user4951


2 Answers

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.

like image 133
JBL Avatar answered Oct 13 '22 11:10

JBL


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.

like image 28
James Kanze Avatar answered Oct 13 '22 12:10

James Kanze