Role of volatile in VC
The volatile keyword is a type modifier that uses the type variables it declares to indicate that it can be changed by unknown factors of Some compilers, such
Operating system, hardware, or other threads. When the variable declared by this keyword is encountered, the compiler does not perform any operations on the code that accesses the variable.
Optimized to provide stable access to special addresses.
An example of using this keyword is as follows:
Int volatile nvint;
When the value of a variable declared by volatile is required, the system always reads data from its memory again, even if
So that data has just been read from this place. The read data is saved immediately.
For example:
Volatile int I = 10;
Int A = I;
... // Other code that does not explicitly tell the compiler to perform operations on I
Int B = I;
Volatile indicates that I may change at any time and must be read from the I address every time it is used. Therefore,
The Assembly Code will re-read data from the I address and put it in B. The optimization method is because the compiler finds that the Code reads data from I twice
The Code does not perform operations on I. It will automatically put the data read last time in B. Instead of reading from I again. In this case, if
I is a register variable or indicates that data on a port is prone to errors, so volatile can ensure stable access to special addresses.
.
Note: In vc6, the Code is not optimized in general debugging mode, so the function of this keyword cannot be seen. Insert the Assembly
Code to test whether the volatile keyword exists and the impact on the final code of the program:
First, use classwizard to create a Win32 console project, insert a voltest. cpp file, and enter the following code:
# Include <stdio. h>
Void main ()
{
Int I = 10;
Int A = I;
Printf ("I = % d \ n", );
// The purpose of the following Assembly statement is to change the I value in the memory, but it does not let the compiler know
_ ASM {
MoV dword ptr [ebp-4], 20 h
}
Int B = I;
Printf ("I = % d \ n", B );
}
Then, run the program in debug version mode and the output result is as follows:
I = 10
I = 32
Then, run the program in release version mode. The output result is as follows:
I = 10
I = 10
The output results obviously show that in the release mode, the compiler optimizes the code and does not output the correct I value for the second time.
Next, we add the volatile keyword to the I statement to see what changes have taken place:
# Include <stdio. h>
Void main ()
{
Volatile int I = 10;
Int A = I;
Printf ("I = % d \ n", );
_ ASM {
MoV dword ptr [ebp-4], 20 h
}
Int B = I;
Printf ("I = % d \ n", B );
}
Run the program in the debug version and release version respectively, and the output is:
I = 10
I = 32
This indicates that this keyword plays its role!