Can someone explain the difference between a static
and const
variable?
Simple and short answer is memory is allocated for static and const only once. But in const that is for only one value where as in static values may change but the memory area remains the same until the end of the program.
const
is equivalent to #define
but only for value statements(e.g. #define myvalue = 2
). The value declared replaces the name of the variable before compilation.
static
is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.
As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.
Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.
public class Test
{
public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct
In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes. In managed languages, the only way to have the effect of a global variable is to declare it as static.
Static variables in the context of a class are shared between all instances of a class.
In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.
When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.
Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.
class myClass {
public:
static const int TOTAL_NUMBER = 5;
// some public stuff
private:
// some stuff
};
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
static value may exists into a function and can be used in different forms and can have different value in the program. Also during program after increment of decrement their value may change but const in constant during the whole program.