The meaning of the const and volatile is:
(1) The section of this procedure can not be modified, any changes are illegal, or at least careless, the compiler should error, to prevent such carelessness;
(2) Another program segment is completely possible to modify, so the compiler is best not to do too radical optimization.
" const" means "use as a constant" instead of "rest assured, it must be a constant".
" volatile" means "Please do not do ghost optimization, this value may be changed," rather than "you can modify this value."
Therefore, they are not contradictory.
The const modified variable does not allow modification here, and does not mean that modifications are not allowed elsewhere, such as:
Copy Code code as follows:
int i = 5;
Const int* p = &i;
*p = 6; not to be;
i = 7; Absolutely, and the "*p" of the "const" is then turned into 7.
For a variable that is not referenced by a pointer, the const volatile does not have much meaning at the same time. Personally feel.
It is necessary to understand that the meaning of "volatile" is not "Non-const". That's why they can be put together.
In the C + + language, const has no antonym, and if a variable does not have a const modifier, it itself is the antonym of the const, not plus volatile is the antonym of the Const.
A typical case of both modifying an object is a read-only register that is used to drive access to external devices.
Leave a question: const volatile int i=10; Is there a problem with this line of code? If not, what exactly is that I attribute?
answer one: no questions, such as a read-only status register. It is volatile because it can be changed unexpectedly; it is a const, because the program should not attempt to modify it. Volatile and const are not contradictory, but the scope of control is not the same, one is outside the program itself, the other is the program itself.
answer two: no problem, const and volatile these two type qualifiers are not contradictory. Const representation (Run-time) constant semantics: A const-decorated object cannot be modified in its scope, and the compiler generates a compilation error for an expression that attempts to modify the const object directly. Volatile represents "variable", in which the Run-time object may be modified outside the control flow of the current program context (for example, a multiple thread is modified by another thread; An object's memory may be randomly modified by multiple hardware devices): An object modified by a volatile, The compiler does not optimize the operation of this object. An object can be modified at the same time by both const and volatile, indicating that the object embodies constant semantics, but may also be modified by unexpected circumstances in the program context in which the current object resides. In addition, LS error, const can modify the left value, the decorated object itself can also be used as a left value (for example, an array).