Volatile is a type modifier (const is also a type modifier). It is designed to modify the variables accessed and modified by different threads.
Role of volatile: as a command keyword, make sure that this command is not omitted due to compiler optimization and requires that the value be read directly each time.
Simply put, it is to prevent the compiler from optimizing the code.
Volatile example:
Hardware registers of parallel devices (for example, Status Registers)
Non-automatic variables accessed in an interrupt service subroutine)
Variables shared by several tasks in multi-threaded applications
Volatile interview questions:
Can a parameter be const or volatile? Explain why.
Can a pointer be volatile? Explain why.
What are the following function errors:
[Cpp]
Int square (volatile int * ptr ){
Return * ptr ** ptr;
}
Answer:
Yes. One example is read-only status registers. It is volatile because it may be unexpectedly changed. It is const because the program should not try to modify it.
Yes. Although this is not very common. One example is when an interrupt service subroutine modifies a pointer to a buffer.
The purpose of this Code is to return the pointer * ptr points to the square of the value. However, since * ptr points to a volatile parameter, the compiler will generate code similar to the following:
[Cpp]
Int square (volatile int * ptr ){
Int a, B;
A = * ptr;
B = * ptr;
Return a * B;
}
* The value of * ptr may be unexpectedly changed, so a and B may be different. As a result, this Code may not return the expected square value! The correct code is as follows:
[Cpp]
Long square (volatile int * ptr ){
Int;
A = * ptr;
Return a *;
}
Volatile instance (VC6 ):
[Cpp]
# 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 );
}
Output:
Then, run the program in debug version mode and the output result is as follows:
[Plain]
I = 10
I = 32
Then, run the program in release version mode. The output result is as follows:
[Plain]
I = 10 www.2cto.com
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.
However, if the volatile keyword is added to the I Declaration, the debugging version and the release version run the program, and the output is:
[Plain]
I = 10
I = 32
Author: deqingguo