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
?
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
?
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:
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.