<p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p>

<p>In my case, I have never knowingly needed it.</p>

[{'answer_id': 72576, 'author': 'ChrisN', 'author_id': 3853, 'author_profile': 'https://Stackoverflow.com/users/3853', 'pm_score': 7, 'selected': False, 'text': "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the <code>volatile</code> keyword to ensure that such accesses aren't optimised away by the compiler.</p>\n"}, {'answer_id': 72617, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 9, 'selected': True, 'text': "<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p>\n\n<p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p>\n\n<pre><code>void waitForSemaphore()\n{\n   volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n   while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n</code></pre>\n\n<p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>\n"}, {'answer_id': 72629, 'author': 'Mladen Janković', 'author_id': 6300, 'author_profile': 'https://Stackoverflow.com/users/6300', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>you must use it to implement spinlocks as well as some (all?) lock-free data structures</li>\n<li>use it with atomic operations/instructions</li>\n<li>helped me once to overcome compiler's bug (wrongly generated code during optimization)</li>\n</ol>\n"}, {'answer_id': 72666, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Developing for an embedded, I have a loop that checks on a variable that can be changed in an interrupt handler. Without "volatile", the loop becomes a noop - as far as the compiler can tell, the variable never changes, so it optimizes the check away.</p>\n\n<p>Same thing would apply to a variable that may be changed in a different thread in a more traditional environment, but there we often do synchronization calls, so compiler is not so free with optimization.</p>\n'}, {'answer_id': 72962, 'author': 'MikeZ', 'author_id': 12402, 'author_profile': 'https://Stackoverflow.com/users/12402', 'pm_score': 6, 'selected': False, 'text': '<p>From a <em>"Volatile as a promise"</em> article by Dan Saks:</p>\n\n<blockquote>\n  <p>(...) a volatile object is one whose value might change spontaneously. That is, when you declare an object to be volatile, you\'re telling the compiler that the object might change state even though no statements in the program appear to change it."</p>\n</blockquote>\n\n<p>Here are links to three of his articles regarding the <code>volatile</code> keyword:</p>\n\n<ul>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025583/Use-volatile-judiciously" rel="noreferrer">Use volatile judiciously</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025609/Place-volatile-accurately" rel="noreferrer">Place volatile accurately</a></li>\n<li><a href="https://www.embedded.com/electronics-blogs/programming-pointers/4025624/Volatile-as-a-promise" rel="noreferrer">Volatile as a promise</a></li>\n</ul>\n'}, {'answer_id': 73520, 'author': 'tfinniga', 'author_id': 9042, 'author_profile': 'https://Stackoverflow.com/users/9042', 'pm_score': 6, 'selected': False, 'text': "<p>Some processors have floating point registers that have more than 64 bits of precision (eg. 32-bit x86 without SSE, see Peter's comment).  That way, if you run several operations on double-precision numbers, you actually get a higher-precision answer than if you were to truncate each intermediate result to 64 bits.</p>\n\n<p>This is usually great, but it means that depending on how the compiler assigned registers and did optimizations you'll have different results for the exact same operations on the exact same inputs.  If you need consistency then you can force each operation to go back to memory by using the volatile keyword.</p>\n\n<p>It's also useful for some algorithms that make no algebraic sense but reduce floating point error, such as Kahan summation.  Algebraicly it's a nop, so it will often get incorrectly optimized out unless some intermediate variables are volatile.</p>\n"}, {'answer_id': 77042, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 2, 'selected': False, 'text': "<p>Beside the fact that the volatile keyword is used for telling the compiler not to optimize the access to some variable (that can be modified by a thread or an interrupt routine), it can be also <strong>used to remove some compiler bugs</strong> -- <em>YES it can be</em> ---.</p>\n\n<p>For example I worked on an embedded platform were the compiler was making some wrong assuptions regarding a value of a variable. If the code wasn't optimized the program would run ok. With optimizations (which were really needed because it was a critical routine) the code wouldn't work correctly. The only solution (though not very correct) was to declare the 'faulty' variable as volatile.</p>\n"}, {'answer_id': 77057, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>A large application that I used to work on in the early 1990s contained C-based exception handling using setjmp and longjmp. The volatile keyword was necessary on variables whose values needed to be preserved in the block of code that served as the "catch" clause, lest those vars be stored in registers and wiped out by the longjmp.</p>\n'}, {'answer_id': 77141, 'author': 'indentation', 'author_id': 7706, 'author_profile': 'https://Stackoverflow.com/users/7706', 'pm_score': 3, 'selected': False, 'text': "<p>I've used it in debug builds when the compiler insists on optimizing away a variable that I want to be able to see as I step through code.</p>\n"}, {'answer_id': 81460, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 3, 'selected': False, 'text': "<p>Besides using it as intended, volatile is used in (template) metaprogramming. It can be used to prevent accidental overloading, as the volatile attribute (like const) takes part in overload resolution.</p>\n\n<pre><code>template &lt;typename T&gt; \nclass Foo {\n  std::enable_if_t&lt;sizeof(T)==4, void&gt; f(T&amp; t) \n  { std::cout &lt;&lt; 1 &lt;&lt; t; }\n  void f(T volatile&amp; t) \n  { std::cout &lt;&lt; 2 &lt;&lt; const_cast&lt;T&amp;&gt;(t); }\n\n  void bar() { T t; f(t); }\n};\n</code></pre>\n\n<p>This is legal; both overloads are potentially callable and do almost the same. The cast in the <code>volatile</code> overload is legal as we know bar won't pass a non-volatile <code>T</code> anyway. The <code>volatile</code> version is strictly worse, though, so never chosen in overload resolution if the non-volatile <code>f</code> is available.</p>\n\n<p>Note that the code never actually depends on <code>volatile</code> memory access.</p>\n"}, {'answer_id': 82306, 'author': 'Frederik Slijkerman', 'author_id': 12416, 'author_profile': 'https://Stackoverflow.com/users/12416', 'pm_score': 5, 'selected': False, 'text': '<p>You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.</p>\n\n<p>To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.</p>\n\n<p>For example, this is how InterlockedIncrement is declared in the Win32 API:</p>\n\n<pre><code>LONG __cdecl InterlockedIncrement(\n  __inout  LONG volatile *Addend\n);\n</code></pre>\n'}, {'answer_id': 17900959, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 3, 'selected': False, 'text': '<p>In Standard C, one of the places to use <code>volatile</code> is with a signal handler.  In fact, in Standard C, all you can safely do in a signal handler is modify a <code>volatile sig_atomic_t</code> variable, or exit quickly.  Indeed, AFAIK, it is the only place in Standard C that the use of <code>volatile</code> is required to avoid undefined behaviour.</p>\n\n<blockquote>\n  <h3>ISO/IEC 9899:2011 §7.14.1.1 The <code>signal</code> function</h3>\n  \n  <p>¶5 If the signal occurs other than as the result of calling the <code>abort</code> or <code>raise</code> function, the\n  behavior is undefined if the signal handler refers to any object with static or thread\n  storage duration that is not a lock-free atomic object other than by assigning a value to an\n  object declared as <code>volatile sig_atomic_t</code>, or the signal handler calls any function\n  in the standard library other than the <code>abort</code> function, the <code>_Exit</code> function, the\n  <code>quick_exit</code> function, or the <code>signal</code> function with the first argument equal to the\n  signal number corresponding to the signal that caused the invocation of the handler.\n  Furthermore, if such a call to the <code>signal</code> function results in a SIG_ERR return, the\n  value of <code>errno</code> is indeterminate.<sup>252)</sup></p>\n  \n  <p><sup>252)</sup> If any signal is generated by an asynchronous signal handler, the behavior is undefined.</p>\n</blockquote>\n\n<p>That means that in Standard C, you can write:</p>\n\n<pre><code>static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n    signal(signum, sig_handler);\n    sig_num = signum;\n}\n</code></pre>\n\n<p>and not much else.</p>\n\n<p>POSIX is a lot more lenient about what you can do in a signal handler, but there are still limitations (and one of the limitations is that the Standard I/O library — <code>printf()</code> et al — cannot be used safely).</p>\n'}, {'answer_id': 39875143, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>volatile</code> keyword is intended to prevent the compiler from applying any optimisations on objects that can change in ways that cannot be determined by the compiler.</p>\n\n<p>Objects declared as <code>volatile</code> are omitted from optimisation because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a <code>volatile</code> object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.</p>\n\n<p><strong>Consider the following cases</strong></p>\n\n<p>1) Global variables modified by an interrupt service routine outside the scope.</p>\n\n<p>2) Global variables within a multi-threaded application.</p>\n\n<p><strong>If we do not use volatile qualifier, the following problems may arise</strong></p>\n\n<p>1) Code may not work as expected when optimisation is turned on.</p>\n\n<p>2) Code may not work as expected when interrupts are enabled and used.</p>\n\n<p><a href="http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766" rel="nofollow">Volatile: A programmer’s best friend</a></p>\n\n<p><a href="https://en.wikipedia.org/wiki/Volatile_(computer_programming)" rel="nofollow">https://en.wikipedia.org/wiki/Volatile_(computer_programming)</a></p>\n'}, {'answer_id': 43802700, 'author': 'bugs king', 'author_id': 1211764, 'author_profile': 'https://Stackoverflow.com/users/1211764', 'pm_score': 1, 'selected': False, 'text': "<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>\n"}, {'answer_id': 46888720, 'author': 'Joachim', 'author_id': 1961484, 'author_profile': 'https://Stackoverflow.com/users/1961484', 'pm_score': 2, 'selected': False, 'text': "<p>Your program seems to work even without <code>volatile</code> keyword? Perhaps this is the reason:</p>\n\n<p>As mentioned previously the <code>volatile</code> keyword helps for cases like</p>\n\n<pre><code>volatile int* p = ...;  // point to some memory\nwhile( *p!=0 ) {}  // loop until the memory becomes zero\n</code></pre>\n\n<p>But there seems to be almost no effect once an external or non-inline function is being called. E.g.:</p>\n\n<pre><code>while( *p!=0 ) { g(); }\n</code></pre>\n\n<p>Then with or without <code>volatile</code> almost the same result is generated.</p>\n\n<p>As long as g() can be completely inlined, the compiler can see everything that's going on and can therefore optimize. But when the program makes a call to a place where the compiler can't see what's going on, it isn't safe for the compiler to make any assumptions any more. Hence the compiler will generate code that always reads from memory directly.</p>\n\n<p>But beware of the day, when your function g() becomes inline (either due to explicit changes or due to compiler/linker cleverness) then your code might break if you forgot the <code>volatile</code> keyword!</p>\n\n<p>Therefore I recommend to add the <code>volatile</code> keyword even if your program seems to work without. It makes the intention clearer and more robust in respect to future changes.</p>\n"}, {'answer_id': 51598967, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 2, 'selected': False, 'text': '<p>In the early days of C, compilers would interpret all actions that read and write lvalues as memory operations, to be performed in the same sequence as the reads and writes appeared in the code.  Efficiency could be greatly improved in many cases if compilers were given a certain amount of freedom to re-order and consolidate operations, but there was a problem with this.  Even though operations were often specified in a certain order merely because it was necessary to specify them in <em>some</em> order, and thus the programmer picked one of many equally-good alternatives, that wasn\'t always the case.  Sometimes it would be important that certain operations occur in a particular sequence.</p>\n<p>Exactly which details of sequencing are important will vary depending upon the target platform and application field.  Rather than provide particularly detailed control, the Standard opted for a simple model: if a sequence of accesses are done with lvalues that are not qualified <code>volatile</code>, a compiler may reorder and consolidate them as it sees fit.  If an action is done with a <code>volatile</code>-qualified lvalue, a quality implementation should offer whatever additional ordering guarantees might be required by code targeting its intended platform and application field, without requiring that programmers use non-standard syntax.</p>\n<p>Unfortunately, rather than identify what guarantees programmers would need, many compilers have opted instead to offer the bare minimum guarantees mandated by the Standard.  This makes <code>volatile</code> much less useful than it should be.  On gcc or clang, for example, a programmer needing to implement a basic &quot;hand-off mutex&quot; [one where a task that has acquired and released a mutex won\'t do so again until the other task has done so] must do one of four things:</p>\n<ol>\n<li><p>Put the acquisition and release of the mutex in a function that the compiler cannot inline, and to which it cannot apply Whole Program Optimization.</p>\n</li>\n<li><p>Qualify all the objects guarded by the mutex as <code>volatile</code>--something which shouldn\'t be necessary if all accesses occur after acquiring the mutex and before releasing it.</p>\n</li>\n<li><p>Use optimization level 0 to force the compiler to generate code as though all objects that aren\'t qualified <code>register</code> are <code>volatile</code>.</p>\n</li>\n<li><p>Use gcc-specific directives.</p>\n</li>\n</ol>\n<p>By contrast, when using a higher-quality compiler which is more suitable for systems programming, such as icc, one would have another option:</p>\n<ol start="5">\n<li>Make sure that a <code>volatile</code>-qualified write gets performed everyplace an acquire or release is needed.</li>\n</ol>\n<p>Acquiring a basic &quot;hand-off mutex&quot; requires a <code>volatile</code> read (to see if it\'s ready), and shouldn\'t require a <code>volatile</code> write as well (the other side won\'t try to re-acquire it until it\'s handed back) but having to perform a meaningless <code>volatile</code> write is still better than any of the options available under gcc or clang.</p>\n'}, {'answer_id': 59002919, 'author': 'curiousguy', 'author_id': 963864, 'author_profile': 'https://Stackoverflow.com/users/963864', 'pm_score': 2, 'selected': False, 'text': '<p>Other answers already mention avoiding some optimization in order to:</p>\n\n<ul>\n<li>use memory mapped registers (or "MMIO")</li>\n<li>write device drivers</li>\n<li>allow easier debugging of programs</li>\n<li>make floating point computations more deterministic </li>\n</ul>\n\n<p>Volatile is essential whenever you need a value to appear to come from the outside and be unpredictable and avoid compiler optimizations based on a value being known, and when a result isn\'t actually used but you need it to be computed, or it\'s used but you want to compute it several times for a benchmark, and you need the computations to start and end at precise points.</p>\n\n<p>A volatile read is like an input operation (like <code>scanf</code> or a use of <code>cin</code>): <em>the value seems to come from the outside of the program, so any computation that has a dependency on the value needs to start after it</em>. </p>\n\n<p>A volatile write is like an output operation (like <code>printf</code> or a use of <code>cout</code>): <em>the value seems to be communicated outside of the program, so if the value depends on a computation, it needs to be finished before</em>.</p>\n\n<p>So <strong>a pair of volatile read/write can be used to tame benchmarks and make time measurement meaningful</strong>.</p>\n\n<p>Without volatile, your computation could be started by the compiler before, <strong>as nothing would prevent reordering of computations with functions such as time measurement</strong>.</p>\n'}, {'answer_id': 61495883, 'author': 'Rohit', 'author_id': 3049983, 'author_profile': 'https://Stackoverflow.com/users/3049983', 'pm_score': 2, 'selected': False, 'text': '<p>All answers are excellent. But on the top of that, I would like to share an example.</p>\n\n<p>Below is a little cpp program:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint x;\n\nint main(){\n    char buf[50];\n    x = 8;\n\n    if(x == 8)\n        printf("x is 8\\n");\n    else\n        sprintf(buf, "x is not 8\\n");\n\n    x=1000;\n    while(x &gt; 5)\n        x--;\n    return 0;\n}\n</code></pre>\n\n<p>Now, lets generate the assembly of the above code (and I will paste only that portions of the assembly which relevant here):</p>\n\n<p>The command to generate assembly:</p>\n\n<pre><code>g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n</code></pre>\n\n<p>And the assembly:</p>\n\n<pre><code>main:\n.LFB1594:\n    subq    $40, %rsp    #,\n    .seh_stackalloc 40\n    .seh_endprologue\n # assembly.cpp:5: int main(){\n    call    __main   #\n # assembly.cpp:10:         printf("x is 8\\n");\n    leaq    .LC0(%rip), %rcx     #,\n # assembly.cpp:7:     x = 8;\n    movl    $8, x(%rip)  #, x\n # assembly.cpp:10:         printf("x is 8\\n");\n    call    _ZL6printfPKcz.constprop.0   #\n # assembly.cpp:18: }\n    xorl    %eax, %eax   #\n    movl    $5, x(%rip)  #, x\n    addq    $40, %rsp    #,\n    ret \n    .seh_endproc\n    .p2align 4,,15\n    .def    _GLOBAL__sub_I_x;   .scl    3;  .type   32; .endef\n    .seh_proc   _GLOBAL__sub_I_x\n</code></pre>\n\n<p>You can see in the assembly that the assembly code was not generated for <code>sprintf</code> because the compiler assumed that <code>x</code> will not change outside of the program. And same is the case with the <code>while</code> loop. <code>while</code> loop was altogether removed due to the optimization because compiler saw it as a useless code and thus directly assigned <code>5</code> to <code>x</code> (see <code>movl    $5, x(%rip)</code>).</p>\n\n<p>The problem occurs when what if an external process/ hardware would change the value of <code>x</code> somewhere between <code>x = 8;</code> and <code>if(x == 8)</code>. We would expect <code>else</code> block to work but unfortunately the compiler has trimmed out that part. </p>\n\n<p>Now, in order to solve this, in the <code>assembly.cpp</code>, let us change <code>int x;</code> to <code>volatile int x;</code> and quickly see the assembly code generated:</p>\n\n<pre><code>main:\n.LFB1594:\n    subq    $104, %rsp   #,\n    .seh_stackalloc 104\n    .seh_endprologue\n # assembly.cpp:5: int main(){\n    call    __main   #\n # assembly.cpp:7:     x = 8;\n    movl    $8, x(%rip)  #, x\n # assembly.cpp:9:     if(x == 8)\n    movl    x(%rip), %eax    # x, x.1_1\n # assembly.cpp:9:     if(x == 8)\n    cmpl    $8, %eax     #, x.1_1\n    je  .L11     #,\n # assembly.cpp:12:         sprintf(buf, "x is not 8\\n");\n    leaq    32(%rsp), %rcx   #, tmp93\n    leaq    .LC0(%rip), %rdx     #,\n    call    _ZL7sprintfPcPKcz.constprop.0    #\n.L7:\n # assembly.cpp:14:     x=1000;\n    movl    $1000, x(%rip)   #, x\n # assembly.cpp:15:     while(x &gt; 5)\n    movl    x(%rip), %eax    # x, x.3_15\n    cmpl    $5, %eax     #, x.3_15\n    jle .L8  #,\n    .p2align 4,,10\n.L9:\n # assembly.cpp:16:         x--;\n    movl    x(%rip), %eax    # x, x.4_3\n    subl    $1, %eax     #, _4\n    movl    %eax, x(%rip)    # _4, x\n # assembly.cpp:15:     while(x &gt; 5)\n    movl    x(%rip), %eax    # x, x.3_2\n    cmpl    $5, %eax     #, x.3_2\n    jg  .L9  #,\n.L8:\n # assembly.cpp:18: }\n    xorl    %eax, %eax   #\n    addq    $104, %rsp   #,\n    ret \n.L11:\n # assembly.cpp:10:         printf("x is 8\\n");\n    leaq    .LC1(%rip), %rcx     #,\n    call    _ZL6printfPKcz.constprop.1   #\n    jmp .L7  #\n    .seh_endproc\n    .p2align 4,,15\n    .def    _GLOBAL__sub_I_x;   .scl    3;  .type   32; .endef\n    .seh_proc   _GLOBAL__sub_I_x\n</code></pre>\n\n<p>Here you can see that the assembly codes for <code>sprintf</code>, <code>printf</code> and <code>while</code> loop were generated. The advantage is that if the <code>x</code> variable is changed by some external program or hardware, <code>sprintf</code> part of the code will be executed. And similarly <code>while</code> loop can be used for busy waiting now.</p>\n'}, {'answer_id': 65641563, 'author': 'alex_noname', 'author_id': 13782669, 'author_profile': 'https://Stackoverflow.com/users/13782669', 'pm_score': 1, 'selected': False, 'text': '<p>I would like to quote Herb Sutter\'s words from his <a href="https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/" rel="nofollow noreferrer">GotW #95</a>, which can help to understand the meaning of the <code>volatile</code> variables:</p>\n<blockquote>\n<p><code>C++</code> <code>volatile</code> variables (which have no analog in languages like <code>C#</code> and <code>Java</code>) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because <code>C++</code> <code>volatile</code> variables aren’t about threads or communication at all and don’t interact with those things. Rather, a <code>C++</code> <code>volatile</code> variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise “strange” and beyond the language. So <code>C++</code> <code>volatile</code> variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler (because the compiler isn’t allowed to know their semantics; a <code>volatile int vi;</code> may not behave anything like a normal <code>int</code>, and you can’t even assume that code like <code>vi = 5; int read_back = vi;</code> is guaranteed to result in <code>read_back == 5</code>, or that code like <code>int i = vi; int j = vi;</code> that reads vi twice will result in <code>i == j</code> which will not be true if <code>vi</code> is a hardware counter for example).</p>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/72552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2167252/']