To talk about my understanding and summary of the volatile keyword, volatile keyword is a C language is not commonly used in a keyword, it is estimated that many people have not heard, our project because of multithreaded design is also used in the volatile keyword, hereby summed up:
1, first of all say compiler optimization.
int i=5;
int a=i;
......
int b=i;
The compiler will put I in the register, and B will take the value directly from the register. The compiler does such optimizations to be quick. But there is a problem, once I was in the memory changed, this is not the result of the error, so in order to avoid compiler optimization error results, volatile keyword can be used to declare I.
2, the application scene, I can use the scenario is that in multi-threaded situations, if a variable is often changed, it is necessary to declare it as volatile type.
3, the typical interview question, as follows:
int square (volatile int * ptr) {
int a=*ptr;
int b=*ptr;
return a*b;
}
So the statement is wrong, because the record that PTR points to may have changed, then it is not squared.
int square (volatile int * ptr) {
int a=*ptr;
return a*a;
}
(End of this article)