tags:

views:

638

answers:

9

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

+6  A: 

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.

Stefan Kendall
There are also static global variables which are static variables declared outside of both a function and a class. I believe the only purpose is for file scoping.
Swiss
@Swiss: yes, `static int fileScopeFoo = 42;` is a deprecated alternative for `namespace { int fileScopeFoo = 42; }`
MSalters
As far as I know, static global variables are not deprecated in C, since there are no namespaces.
Swiss
+1  A: 

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.

Harley Green
+1  A: 

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
};
Xorlev
A: 

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.

mateuszb
In C++, the anonymous namespace is preferred to static for file scope variables.
Jonathan Leffler
A: 

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.

this. __curious_geek
+2  A: 

A static variable can get an initial value only one time. This means that if you have a code such as "static int a=0" in sample function, and this code executed in first call of this function, then in next execution of function this code doesn't execute and variable (a) still has its current value (for example a current value is 5), because the static variable get initial value one time.

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

celine
A: 

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

manugupt1
+1  A: 

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, the use of the static keyword is deprecated when declaring objects in namespace scope will be deprecated.

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.

dirkgently
I don't understand why `static int y = -42;` would be an error. It's arguably not quite smart to do it, but it is very much legal, i think. (see http://stackoverflow.com/questions/2217628/multiple-definition-of-inline-functions-when-linking-static-libs/2218034#2218034 )
Johannes Schaub - litb
@litb: Because, inline definition of functions are not allowed to have modifiable static object definitions in C99. See 6.7.4. para 3 and a related footnote on the next page (possibly).
dirkgently
@dirkgently, ah thanks. Haven't known this.
Johannes Schaub - litb
Do you know the reason for that restriction? I mean, the inline definitions are already allowed to expose different behavior. Why are they then limited to non-modifiable object definitions and forbidden to use identifiers with internal linkage? I imagine such static variables could be useful for debugging/etc. Any idea?
Johannes Schaub - litb
@litb: If it is non-const, then per footnote "120) 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." of the draft and 6.7.4 para 6, IMO, at any given time, the value of the object will be indeterminable (the value can come from either the external definition/internal definition based on how and where what choice the compiler had made.
dirkgently
A: 

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