title: How is in-class static const initialization of float different from int in C++?
body: <p>I have a class with <code>static const</code> members that I'm initializing inside the class declaration:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class Foo
  {
      public:
          static const int i = 9;
          static const float f = 2.9999;
  };
  
  int main()
  {
      std::cout &lt;&lt; Foo::i &lt;&lt; std::endl;
      std::cout &lt;&lt; Foo::f &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>When compiled with GCC 4.8.2 with option <code>--std=c++11</code>, it gives this compile error:</p>
  
  <pre><code>foo.cpp:7:32: error: ‘constexpr’ needed for in-class initialization of static data member ‘const float Foo::f’ of non-integral type [-fpermissive]
           static const float f = 2.9999;
                                  ^
  </code></pre>
  
  <p>As the message indicates, the error goes away if the line is changed to <code>static constexpr float f = 2.9999;</code>.</p>
  
  <p>Why should the in-class static const initialization of a floating-point variable be any different from a integral variable? Aren't they both just a value of certain size (number of bytes) that is copied over (like a macro) or referred to using a pointer?</p>
  
  <p>Some older answers to similar (not the same) questions on SO indicate that this is because floating point expressions might give different results between the compiled machine and the execution machine (assuming a cross-compilation scenario).</p>
  
  <p>However:</p>
  
  <ol>
  <li><p>the above code assigns a value directly, there is no arithmetic operation that needs to be performed to compute a value</p></li>
  <li><p>there might be different results for integral expressions too since its underflow and overflow results are not unambiguously defined across different architectures. </p></li>
  <li><p>Finally, what magic does <code>constexpr</code> do here that <code>const</code> does not? Why doesn't the language just do what <code>constexpr</code> does when <code>const</code> is used? I mean, why another keyword when the following statements work fine as C++ code outside a class anyway:
  <code>
  const int i = 9;
  const float f = 2.9999;
  </code></p></li>
  </ol>