Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - What is the difference between constants and statics in C++?
What is the difference between constants and statics in C++?

In the global domain, whether const or static means it is unique in memory.

The difference is that const is truly unique, not only having a unique address, but also a unique value;

static only has a unique address, and its value can be changed.

In a local domain, such as a class, const loses the uniqueness of the address and retains the uniqueness of the value, because a class has many objects, and the addresses of each object must be different.

The most interesting thing is static, which becomes a common address for all objects. If you still like to use const static at this time, it is better to use a global const

About static constants ( static const)?

This concept should not exist.

Because, this is not as good as declaring an unnamed enum or an unnamed namespace.

Constant means: "Cannot be modified! Or it is strongly recommended not to modify it!", const only shows that the variable (or function) cannot be modified (or does not modify others).

Static means: "It is a variable in the static data area", static affects the scope and storage area of ??the variable.

In fact, the C++ standard does not support the use of the keyword static in namespaces and global scopes (the standard uses "deprecated" to indicate that this practice is currently legal, but it is likely to be regarded as is illegal).

For example, the following code:

static int nCount;

int fun1();

int main()

{

}

int fun1()

{

}

The C++ standard means that programmers should do this:

namespace

{

int nCount;

}

int fun1();

int main()

{

}

int fun1()

{

}