C language volatile and const use should be aware of the problem

  • 2020-04-02 01:35:07
  • OfStack

The meaning of const and volatile together is:

(1) no modification can be made to a in this program segment. Any modification is illegal or at least careless. The compiler should report an error to prevent such carelessness.

(2) the other segment is completely open to modification, so it is best not to optimize too aggressively.

"Const" It means "use as a constant", not "don't worry, it's a constant".
"Volatile" "Please do not do random optimizations, this value may change", not "you can modify this value".
So they are not contradictory in the first place.

Just because a const modified variable is not allowed to be modified here does not mean that it is not allowed to be modified elsewhere, for example:


int i = 5;
const int* p = &i;
*p = 6; //Can't;
i = 7; //Absolutely, and that "*p" for "const" then becomes 7.

For variables that are not Pointers or references, const volatile does not make much sense at the same time. Personally.

It is important to understand that "volatile" does not mean "non-const". That's why they can be put together.
In C++, const has no antonym. If a variable is not decorated with const, it is an antonym of const. Volatile is not the antonym of const.

A typical case in which both modify an object is a read-only register used to access an external device in a driver.

Const volatile int I =10; Is there a problem with this line of code? If not, what property is I?

Answer a: No problems, such as read-only status registers. It is volatile because it can be changed unexpectedly; It's const because the program shouldn't try to change it. Volatile and const are not contradictory, but the scope of control is different, one is outside the program itself, the other is the program itself.

Answer two: No problem. The two types of qualifiers, const and volatile, do not conflict. Const represents (runtime) constant semantics: objects modified by const cannot be modified in their scope, and the compiler generates compilation errors for expressions that attempt to modify const objects directly. Volatile stands for "volatile," meaning that an object at run time may be modified outside of the current program context's control flow (for example, in multiple threads; The memory in which the object resides may be randomly modified by multiple hardware devices, etc.) : the compiler does not optimize the operation of an object that is modified with volatile. An object can be decorated with both const and volatile to indicate that the object embodies constant semantics, but can also be modified by unexpected circumstances in the context of the program in which the current object resides. In addition, LS errors, const can be used to modify lvalues, and the object itself can be used as an lvalue (such as an array).


Related articles: