Type modifier volatile - C++

Preface 

In the process of daily study, I saw the type modifier volatile and didn't know how to use it, so I looked up the information and learned it.

theory

The volatile keyword is a type modifier . When a variable is declared using volatile, the system always re-reads the data from the memory where it is located , even if the previous instruction has just read the data from there (the compiler no longer controls the access code for this variable is optimized).

Example

Execute the code

#include <stdio.h>
 
void main()
 
{
 
int i=10;
 
int a = i;
 
printf("i= %d/n",a);
 
//下面汇编语句的作用就是改变内存中i的值,但是又不让编译器知道
 
__asm {
 
 mov dword ptr [ebp-8], 20h
 
}
 
 
 
int b = i;
 
printf("i= %d/n",b);
 
}

When running the program in debug version mode, the output is as follows:

i = 10

i = 32

Then, run the program in release version mode, and the output results are as follows:

i = 10

i = 10

The reason for this result is that optimization is performed in release mode: the compiler finds that the code between the two codes that read data from i has not operated on i, and it will automatically put the last read data in b.

If you add the modifier volatile to the declaration of variable i, so that every time the data is read, it is read from the address, and the above problem will not occur again.

volatile int i=10;

 To add, the above code I refer to is written online. The original offset value in the assembly is 4. I looked at the top of the stack through debugging.

Applicable scene

  • Hardware registers of parallel devices (such as status registers)
  • Non-automatic variables accessed in an interrupt service routine (Non-automatic variables)
  • Variables shared by several tasks in multi-threaded applications

Conclusion

So be it!

Guess you like

Origin blog.csdn.net/xiaopei_yan/article/details/128468381