The meaning and usage of volatile

The meaning and usage of volatile

Preface

I was asked the question about volatile a few days ago. To be honest, my understanding of volatile is limited to the level of preventing it from being optimized by the compiler, but I don’t know what kind of occasions it actually needs to be applied to. Therefore, yesterday’s question of volatile After re-learning, I also decided to write it down and record it.

Definition of volatile

Volatile is a feature modifier, a keyword on the compiler, just like static and const. Its ultimate purpose is to prevent the instruction that needs to be executed from being optimized by the compiler. A volatile variable means that the variable may be changed unexpectedly, so that the compiler will not assume the value of this variable.

effect

Its function is not too magical, you can take a look at it for example,
EX1:
In a program like this:

AX_1 = 0;
AX_1 = 1;
AX_1 = 2;
AX_1 = 3;
AX_1 = 4;

I have no idea that the value of AX_1 is 4 at the end, but if I ask you, in this code, has AX_1 experienced a change from 0-4? The answer is not necessarily, why? Because in different compiler environments, the optimization level of the code is different, and some are even set to no optimization effect. Using Keil as an example,
Insert picture description here
many optimization levels will directly default to the -O3 level. The higher the optimization level, the smaller the size of the generated firmware, but if you don’t pay attention to many details during programming, it will Optimized directly by the compiler. Of course, under this condition, it is impossible for AX_1 to manage a 0-4 change, it will be directly omitted from a 0-3 change and directly reach 4. Here I actually have a question at the same time, suppose AX_1 is a status register? Of course, it is generally not used to assign values ​​to registers.

EX2:
Unexpected events, such as interrupts.
In fact, it can be understood from the italicized words in the definition of volatile, "This variable may be changed unexpectedly." Isn't interrupt just doing such a thing? For interrupts, events can be executed periodically or acyclically, but they are all burst processing. If an interrupt is suddenly entered, and then a certain value is modified, it is actually An unexpected change, sudden. Therefore, using volatile to modify the variables that need to be modified can well avoid this problem. Of course, it may also be possible to reduce the optimization level of the compiler, but the places that need to be optimized by the compiler are not optimized. It seems wasteful to say, so it's a good thing to be able to write more standardized.

Guess you like

Origin blog.csdn.net/qq_42312125/article/details/108483514