The difference between static variable static and constant const

common ground:

1. Static and const allocate memory directly at compile time.

the difference:

1. (Essential) static is a type reference, and const is an instance reference.

2. (Initialization) The initial value of a static variable must be a constant. Static initial values ​​default to 0, and constants also default to 0 (?).

3. (Assignment) The value of a static variable can be changed at runtime, while the value of a constant cannot be changed. It has been fixed at the beginning of the operation, and an error will be reported if it is modified later.

4. (Memory) Static variables are stored in the global data area. With this program flow, the value of this variable can be preserved until the next call. However, static variables with too large data may cause memory leaks. The const constant is regarded as an ordinary read-only variable, which ends with the end of the function. In C, const constants are always allocated memory, located in the read-only data segment. In C++, if the const constant is not declared as extern, then it is a compile-time symbol and does not occupy memory.

Precautions:

————————————————————————

Why does this example in C language report an error?

const int n = 5;   

int a[n];

——————————————————

For ANSI C compilers, const variables are not equal to real constants. Constants do not exist in the program, so they are read-only. The "read-only variable" is to open up a place in memory to store its value, but this value is restricted by the compiler and cannot be modified. The C language keyword const is a modifier (Qualifier) ​​used to limit a variable that is not allowed to be changed. In the above code, the variable n is modified as a read-only variable, but unfortunately it is not a constant no matter how modified it is. However, ANSI C stipulates that the dimension must be "constant" when defining an array, and "read-only variables" are also not allowed.

Reference article:

What is the specific difference between static variables and constants in C#?

The difference between procedural and object-oriented static keywords

Will this static constant cause a memory leak? Why

Do const constants occupy memory in the space?

Do CONST constants take up memory?

Reprint: The difference between static variables and constants_The difference between static constants and constants_haobaworenle's blog-CSDN blog

Guess you like

Origin blog.csdn.net/weixin_42565127/article/details/130866471
Recommended