Difference between const and static const

Hi,

Please explain difference between const and static const, more effectively. If it is possible pls explain with example.

Note: I know the basic concept of const and static but I need clear explanation of declaring "const" and "static const"

Ex: const int a;
static const int a;
static is not related to const.

const says that the variable's name can't be used to modify its value.
static says that the variable is stored in static storage (just like global variables).

http://en.wikipedia.org/wiki/Static_variable

If your a variables are global, then things get a bit more complicated, as in C++ const variables have internal linkage.

This renders the second meaning of static (which is inherited from C) useless. Also in C++ you should use the unnamed namespace for this.

http://stackoverflow.com/questions/2271902/static-vs-global/2271930
http://stackoverflow.com/questions/8346991/linking-with-constant-variable-definition-in-a-header-file
http://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static
static in a class means the object has a global lifetime (but scope local to the class). That is... all instances of the class share the same static objects.

static in local scope means the object is constructed once upon first use, then retains its value between functions calls (As if it were global, but with local scope). That is.... all calls to the function share the same static objects.

So static basically means "global lifetime, but smaller scope"

This is often combined with const because for constants, there is no reason to create unique copies since they'd all be the same.

For example:

1
2
3
4
5
6
7
8
9
void checkMyString(std::string foo)
{
    static const std::string expected = "Some fixed string.";

    if(foo == expected)
    {
        // do something
    }
}


static makes sense here because without it, the 'expected' string will be constructed/destructed every time the function is called*. Whereas if you make it static, it's guaranteed to be constructed/destructed exactly once.

(However, note the downside here is that 'checkMyString' will no longer be threadsafe, as multiple threads may attempt to construct the string simultaneously)

* maybe... depending on compiler optimizations...
note the downside here is that 'checkMyString' will no longer be threadsafe, as multiple threads may attempt to construct the string simultaneously

it is guaranteed to be thread-safe in C++11
Ah, that's news to me! And also awesome.
Thanks to all for giving valuable information.
Topic archived. No new replies allowed.