Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c++ - What is the use of volatile keyword?

What is the use of volatile keyword in C/C++? What is the difference between declaring a variable volatile and not declaring it as volatile?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The volatile qualifier on a variable tells the compiler that whenever you access this variable, its value has to be loaded from memory, and that the compiler may assume nothing about this value from previous stores it has effected.

So it is appropriate whenever you have situations where a variable may have a value that can not be foreseen in the current "thread of execution" (in a broad sense). This includes:

  • hardware registers
  • status variables in signal handlers
  • live variables that are used after unexpected jumps such as goto, switch/case, or, more important, setjmp/longjmp.

volatile is also necessary (but not sufficient!) for atomic access to thread shared variables to which the access is not mutexed. For that purpose volatile is by no means sufficient to guarantee the atomic access, even if it is just for reading. For that, you'd have to use special instructions of the CPU that are not modeled (or interfaced) by the abstract machine of the current C standard, C99. The next standard, C1X, is supposed to have such primitives.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...