Problem
What exactly does const in C and C ++ indicate? How is the specific implementation mechanism implemented? This article will analyze the two issues and briefly explain the meaning and Implementation Mechanism of Const.
Problem Analysis
To put it simply, const represents a read-only variable in C language and a constant in C ++ language.
C const example:
Copy the Code as follows:
Const int I = 10;
Int * P = (int *) (& I );
* P = 20;
Printf ("I = % d * P = % d \ n", I, * P );
Guess what the output result is? I = 20 * P = 20
C ++ const Example 1:
Copy the Code as follows:
Const int I = 10;
Int * P = const_cast <int *> (& I );
* P = 20;
Cout <"I =" <I <"* P =" <* P <Endl;
The output result is I = 10 * P = 20.
C ++ const Example 2:
Copy the Code as follows:
Struct test {
Int J;
Char TMP;
Test ()
{
J = 30;
TMP = 'a ';
}
};
Int main (INT argc, char * argv [])
{
Const struct test T1;
Int * q = (int *) (& t1.j );
* Q = 40;
Cout <"J =" <t1.j <"* q =" <* q <Endl;
Return 0;
}
The output result is J = 40 * q = 40.
Sample Result Analysis
Are you surprised to see the above three output results:
Question 1: For variable I of the const int type, after the value is changed through the pointer P in C language, I is changed to 20. In C ++, after the value is modified through the pointer P, the I is still 10.
Question 2: The element J of const struct test in C ++ is changed through the pointer Q. Why is the reaction mechanism of const int different from that of const struct test?
To address Issue 1, we know that const in C indicates a read-only variable. Since const is regarded as a variable, it will have storage space in the memory, in addition, the value of the memory space can be indirectly changed through the pointer. When the value in the memory is changed through the pointer P and the value of I is obtained, the space will be accessed, the result is the changed value. C ++ regards const as a constant, and the compiler will directly replace the reference to I with constants, such as cout <I;
It will be understood as cout <10; it will not access the memory address of I to retrieve data. Here it is a bit like the macro # define I 10 in the C language. Therefore, in C ++, I will output 10, and * P will output 20.
For problem 2, c ++ only replaces the built-in data types with constants, but not the built-in data types such as struct. Because the struct type is not a built-in data type, the compiler does not know how to replace it directly. Therefore, you must access the memory to retrieve data, and access to the memory to retrieve data will inevitably get the value after the Q pointer changes, therefore, const
The Int type is completely different in the processing mode.
Code:
Const int I = 0;
I = 10; // compilation is the same.
Int * P = (int *) & I;
P = 10; // yes.
Therefore, It is inferred that the const mechanism is implemented by the compiler rather than the read-only memory.