What is a static variable?
Basically what my subject says, what is a static variable?? And why would someone would want to use one? Thanks in advance.
|
when something is static, it does not get changed. you use statics so that these variables are impossible to change because they are there to serve one purpose. when you are first writing programs, you may not use to many, if any, statics, but later on they come in handy when writing programs with a lot of functionality.
|
thanks a lot... they seem to be similar to constants... which as I think of it.. what is the diff between a static variable and a constant?
|
static variables (when inside a function) don't go away when the function exits. For instance, say you have this program:
Code:
void myfunc(void) Code:
void myfunc(void) So it's not that the variable doesn't change, it's just that the variable doesn't get recreated every time you call the function. |
Here, this will tell you all you need to know about static variables:
http://www-ee.eng.hawaii.edu/Courses...on2.1.1.6.html (picked up from a simple "What is a static variable?" query on google. |
Saying a static variable doesn't get (its value) changed is wrong, one can change the value of a static (non-const) variable just like any other non-const variable (and, yes, I know you can "cast away" constness). Having said that, it's common to use static together with const when declaring constants that you don't want several instances of (that would just waste memory). The thing that separates static variables from normal (automatic) variables is that they exist during the life time of their translation unit (read: file), instead of the current scope as the case is for automatic variables. For example, in C++, and static member variable could be used to keep track of the number of instances of a class. I use statics from time to time, often when dealing with callbacks, or when declaring global constant variables.
|
Another thing to keep in mind is when "static" is used in front of a global
variable (one not declared within a function), then the meaning is quite different. In that case "static" indicates that the name (of the global) is local to the file. |
I'm sorry, my mind wasn't connected to my mouth (fingers)...
My previous comment about "static" applies before a function, not a variable. |
All times are GMT -5. The time now is 05:07 AM. |