title: Is the compiler allowed to constant-fold a local volatile?
body: <p>Consider this simple code:</p>
  
  <pre><code>void g();
  
  void foo()
  {
      volatile bool x = false;
      if (x)
          g();
  }
  </code></pre>
  
  <p><a href="https://godbolt.org/z/I2kBY7" rel="noreferrer">https://godbolt.org/z/I2kBY7</a></p>
  
  <p>You can see that neither <code>gcc</code> nor <code>clang</code> optimize out the potential call to <code>g</code>. This is correct in my understanding: The abstract machine is to assume that <code>volatile</code> variables may change at any moment (due to being e.g. hardware-mapped), so constant-folding the <code>false</code> initialization into the <code>if</code> check would be wrong.</p>
  
  <p>But MSVC eliminates the call to <code>g</code> entirely (keeping the reads and writes to the <code>volatile</code> though!). Is this standard-compliant behavior?</p>
  
  <hr>
  
  <p><sup>Background: I occasionally use this kind of construct to be able to turn on/off debugging output on-the-fly: The compiler has to always read the value from memory, so changing that variable/memory during debugging should modify the control flow accordingly. The MSVC output does re-read the value but ignores it (presumably due to constant folding and/or dead code elimination), which of course defeats my intentions here.</sup></p>
  
  <hr>
  
  <p>Edits:</p>
  
  <ul>
  <li><p>The elimination of the reads and writes to <code>volatile</code> is discussed here: <a href="https://stackoverflow.com/questions/51472394/is-it-allowed-for-a-compiler-to-optimize-away-a-local-volatile-variable?noredirect=1&amp;lq=1">Is it allowed for a compiler to optimize away a local volatile variable?</a> (thanks Nathan!). I think the standard is abundantly clear that those reads and writes <em>must</em> happen. But that discussion does not cover whether it is legal for the compiler to take the <em>results</em> of those reads for granted and optimize based on that. I suppose this is <a href="http://eel.is/c++draft/dcl.type.cv#6" rel="noreferrer">under-/unspecified</a> in the standard, but I'd be happy if someone proved me wrong.</p></li>
  <li><p>I can of course make <code>x</code> a non-local variable to side-step the issue. This question is more out of curiosity.</p></li>
  </ul>