What is the difference between a static and const variable?

C++CStaticConstants

C++ Problem Overview


Can someone explain the difference between a static and const variable?

C++ Solutions


Solution 1 - C++

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

These two concepts are not mutually exclusive, and can be used together.

Solution 2 - C++

The short answer:

A const is a promise that you will not try to modify the value once set.

A static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.

C99 borrowed the use of const from C++. On the other hand, static has been the source of many debates (in both languages) because of its often confusing semantics.

Also, with C++0x until C++11 the use of the static keyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).

The longer answer: More on the keywords than you wanted to know (right from the standards):

C99

#include <fenv.h>
#pragma STDC FENV_ACCESS ON

/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage

int i2; // external linkage, automatic duration (effectively lifetime of program)

int *p = (int []){2, 4}; // unnamed array has static storage

/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"}  // static, non-modifiable


void f(int m)
{
    static int vla[ m ]; // err

    float w[] = { 0.0/0.0 }; // raises an exception

    /* block scope, static storage, no-linkage */
    static float x = 0.0/0.0; // does not raise an exception
    /* ... */
     /* effect on string literals */
    char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
    char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
    const char *cp = (const char []){"/tmp/fileXXXXXX"}  // automatic storage, non-modifiable

}

inline void bar(void)
{
     const static int x = 42; // ok
     // Note: Since an inline definition is distinct from the 
     // corresponding external definition and from any other
     // corresponding inline definitions in other translation 
     // units, all corresponding objects with static storage
     // duration are also distinct in each of the definitions
     static int y = -42; // error, inline function definition
}

// the last declaration also specifies that the argument 
// corresponding to a in any call to f must be a non-null 
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);

static void g(void); // internal linkage

C++

Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying statics.

extern "C" {
static void f4(); // the name of the function f4 has
                  // internal linkage (not C language
                  // linkage) and the function’s type
                  // has C language linkage.
}

class S {
   mutable static int i; // err
   mutable static int j; // err
   static int k; // ok, all instances share the same member
};

inline void bar(void)
{
     const static int x = 42; // ok
     static int y = -42; // ok
}

There are a few more nuances of C++'s static that I leave out here. Have a look at a book or the standard.

Solution 3 - C++

Static Variables:

  • Initialized only once.
  • Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
  • Value persists between different function calls

Const Variables:

  • Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.

Solution 4 - C++

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.

Solution 5 - C++

Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.

Check out this site.

Solution 6 - C++

static is a storage specifier.
const is a type qualifier.

Solution 7 - C++

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.

Solution 8 - C++

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

Solution 9 - C++

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
};

Solution 10 - C++

static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.

const is just constant, meaning can't be modified.

Solution 11 - C++

Const means “cannot be changed.”

Static means “static instance (in memory) vs dynamic instance (on the stack.)” Static variables exist for the duration of the program. Dynamic ones are created and destroyed as needed.

A variable can be one or both.

Solution 12 - C++

const means constant and their values are defined at compile time rather than explicitly change it during run time also, the value of constant cannot be changed during runtime

However static variables are variables that can be initialised and changed at run time. However, static are different from the variables in the sense that static variables retain their values for the whole of the program ie their lifetime is of the program or until the memory is de allocated by the program by using dynamic allocation method. However, even though they retain their values for the whole lifetime of the program they are inaccessible outside the code block they are in

For more info on static variables refer here

Solution 13 - C++

Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.

Solution 14 - C++

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.

Solution 15 - C++

static keyword defines the scope of variables whereas const keyword defines the value of variable that can't be changed during program execution

Solution 16 - C++

> static

is used for making the variable a class variable. You need not define a static variable while declaring.

Example:

#include <iostream>

class dummy
{
        public:
                static int dum;
};


int dummy::dum = 0; //This is important for static variable, otherwise you'd get a linking error

int main()
{
        dummy d;
        d.dum = 1;

        std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
        std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;

        return 0;
}

This would print: Printing dum from object: 1 Printing dum from class: 1

The variable dum is a class variable. Trying to access it via an object just informs the compiler that it is a variable of which class. Consider a scenario where you could use a variable to count the number of objects created. static would come in handy there.

> const

is used to make it a read-only variable. You need to define and declare the const variable at once.

In the same program mentioned above, let's make the dum a const as well:

class dummy
{
        public:
                static const int dum; // This would give an error. You need to define it as well
                static const int dum = 1; //this is correct
                const int dum = 1; //Correct. Just not making it a class variable

};

Suppose in the main, I am doing this:

int main()
{
        dummy d;
        d.dum = 1; //Illegal!

        std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
        std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;

        return 0;
}

Though static has been manageable to understand, const is messed up in c++. The following resource helps in understanding it better: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

Solution 17 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjaiminView Question on Stackoverflow
Solution 1 - C++Stefan KendallView Answer on Stackoverflow
Solution 2 - C++dirkgentlyView Answer on Stackoverflow
Solution 3 - C++user3681970View Answer on Stackoverflow
Solution 4 - C++ThunderGrView Answer on Stackoverflow
Solution 5 - C++H. GreenView Answer on Stackoverflow
Solution 6 - C++Parveen KumarView Answer on Stackoverflow
Solution 7 - C++this. __curious_geekView Answer on Stackoverflow
Solution 8 - C++celineView Answer on Stackoverflow
Solution 9 - C++XorlevView Answer on Stackoverflow
Solution 10 - C++invalidopcodeView Answer on Stackoverflow
Solution 11 - C++Kiki JewellView Answer on Stackoverflow
Solution 12 - C++manugupt1View Answer on Stackoverflow
Solution 13 - C++user266117View Answer on Stackoverflow
Solution 14 - C++shivapolaView Answer on Stackoverflow
Solution 15 - C++sumeraView Answer on Stackoverflow
Solution 16 - C++AparnaView Answer on Stackoverflow
Solution 17 - C++kanwal kumar maheshwariView Answer on Stackoverflow