What is the difference between a static and const variable?

前端 未结 17 1753
天命终不由人
天命终不由人 2020-11-29 18:39

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

相关标签:
17条回答
  • 2020-11-29 18:49
    static is a storage specifier.
    const is a type qualifier.
    
    0 讨论(0)
  • 2020-11-29 18:50

    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.

    0 讨论(0)
  • 2020-11-29 18:50

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

    0 讨论(0)
  • 2020-11-29 18:51

    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.

    0 讨论(0)
  • 2020-11-29 18:54

    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.
    0 讨论(0)
  • 2020-11-29 18:54

    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

    0 讨论(0)
提交回复
热议问题