The following is an analysis of the volatile keyword that I searched from the Internet ......
A variable defined as volatile means that this variable may be unexpectedly changed, so that the compiler will not assume the value of this variable. Precisely, the optimizer must carefully re-read the value of this variable every time when using this variable, rather than using the backup stored in the register. The following are examples of volatile variables: 1). Hardware registers of parallel devices (for example, Status Registers) 2). An interrupt service sub- Program Non-automatic variables that will be accessed in (non-automatic variables) 3). The variables shared by several tasks in a multi-threaded application cannot answer this question and will not be hired. I think this is the most basic problem to distinguish between C programmers and embedded system programmers. Embedded System programmers often deal with hardware, interruptions, RTOS, and so on, all of which require volatile variables. If you do not know volatile content, it will lead to disasters. If the subject correctly answers this question (well, I doubt this will happen), I will go a little deeper to see if this guy understands the full importance of volatile. 1) can a parameter be const or volatile? Explain why. 2) can a pointer be volatile? Explain why. 3) What is the error in the following function: int square (volatile int * PTR) {return * PTR ** PTR;} The answer below is: 1). 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. 2). Yes. Although this is not very common. One example is when a service subroutine repairs a pointer to a buffer. 3). This section Code There is a prank. 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: 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: Long square (volatile int * PTR) {int A; A = * PTR; return a * ;}