Original address:
Http://www.cnblogs.com/yc_sunniwell/archive/2010/06/24/1764231.html
The volatile reminder compiler can change the variables that are defined later, so the compiled program reads the data directly from the variable address each time it needs to store or read the variable. Without the volatile keyword, the compiler might optimize reading and storage, may temporarily use the value in the register, and if the variable was updated by another program, there would be an inconsistency. The following examples illustrate. In DSP development, it is often necessary to wait for an event to be triggered, so the program is often written like this:
Short flag;
void Test ()
{
Do1 ();
while (flag==0);
Do2 ();
}
This program waits for the value of the memory variable flag to change to 1 (suspect here is 0, a little doubt) before running Do2 (). The value of the variable flag is changed by another program, which may be a hardware interrupt service program. For example, if a button is pressed, the DSP will be interrupted, the key in the interrupt program to modify flag 1, so that the above program can continue to run. However, the compiler does not know that the value of flag will be modified by another program, so when it is optimized, the value of flag may be read into a register first, and then wait for that register to become 1. If such optimizations are unfortunate, then the while loop becomes a dead loop because the contents of the register cannot be modified by the Interrupt service program. In order for the program to read the value of the TRUE flag variable every time, it needs to be defined as follows:
volatile short flag;
It is important to note that there may be no volatile or normal operation, but it is possible to modify the compiler's optimization level and not run properly. As a result, the debug version is normal, but the release version is not a normal issue. So for security reasons, just wait for another program to modify a variable, plus the volatile keyword.
C-language volatile