title: Different floating point result with optimization enabled - compiler bug?
body: <p>The below code works on Visual Studio 2008 with and without optimization. But it only works on g++ without optimization (O0).</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  #include &lt;cmath&gt;
  
  double round(double v, double digit)
  {
      double pow = std::pow(10.0, digit);
      double t = v * pow;
      //std::cout &lt;&lt; "t:" &lt;&lt; t &lt;&lt; std::endl;
      double r = std::floor(t + 0.5);
      //std::cout &lt;&lt; "r:" &lt;&lt; r &lt;&lt; std::endl;
      return r / pow;
  }
  
  int main(int argc, char *argv[])
  {
      std::cout &lt;&lt; round(4.45, 1) &lt;&lt; std::endl;
      std::cout &lt;&lt; round(4.55, 1) &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>The output should be:</p>
  
  <pre><code>4.5
  4.6
  </code></pre>
  
  <p>But g++ with optimization (<code>O1</code> - <code>O3</code>) will output:</p>
  
  <pre><code>4.5
  4.5
  </code></pre>
  
  <p>If I add the <code>volatile</code> keyword before t, it works, so might there be some kind of optimization bug?</p>
  
  <p>Test on g++ 4.1.2, and 4.4.4.</p>
  
  <p>Here is the result on ideone:
  <a href="http://ideone.com/Rz937">http://ideone.com/Rz937</a></p>
  
  <p>And the option I test on g++ is simple:</p>
  
  <pre><code>g++ -O2 round.cpp
  </code></pre>
  
  <p>The more interesting result, even I turn on <code>/fp:fast</code> option on Visual Studio 2008, the result still is correct.</p>
  
  <p><strong>Further question:</strong></p>
  
  <p>I was wondering, should I always turn on the <code>-ffloat-store</code> option?</p>
  
  <p>Because the g++ version I tested is <strong>shipped with <a href="http://en.wikipedia.org/wiki/CentOS">CentOS</a>/<a href="http://en.wikipedia.org/wiki/Red_Hat_Linux">Red Hat Linux</a> 5 and CentOS/Redhat 6</strong>.</p>
  
  <p>I compiled many of my programs under these platforms, and I am worried it will cause unexpected bugs inside my programs. It seems a little difficult to investigate all my C++ code and used libraries whether they have such problems. Any suggestion?</p>
  
  <p>Is anyone interested in why even <code>/fp:fast</code> turned on, Visual Studio 2008 still works? It seems like Visual&nbsp;Studio&nbsp;2008 is more reliable at this problem than g++?</p>