title: Initial value of primitive data-types
body: <pre><code>#include &lt;iostream&gt;
  
  class MyClass
  {
  public:
      MyClass() :
          mFirst()
      {
      }
  
      int mFirst;
      int mSecond;
  };
  
  
  int main()
  {
      MyClass mc;
      std::cout &lt;&lt; "mc.mFirst: " &lt;&lt; mc.mFirst &lt;&lt; std::endl;
      std::cout &lt;&lt; "mc.mSecond: " &lt;&lt; mc.mSecond &lt;&lt; std::endl;
  
      int a;
      std::cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>What is the expected output of this program?</p>
  
  <p>I would think only <code>MyClass.mFirst</code> will be initialized to zero. However GCC initializes them all to zero, even with optimizations enabled:</p>
  
  <pre><code>$ g++ -o test -O3 main.cpp
  $ ./test
  mc.mFirst: 0
  mc.mSecond: 0
  a: 0
  </code></pre>
  
  <p>I'd like to know:</p>
  
  <ol>
  <li>How is each value initialized according to the C++ standard?</li>
  <li>Why does GCC initialize them all to zero?</li>
  </ol>
  
  <h3>Update</h3>
  
  <p>According to Erik the values are zero because my stack happens to contain zeroes. I tried forcing the stack to be non-zero using this construct:</p>
  
  <pre><code>int main()
  {
      // Fill the stack with non-zeroes
      {
          int a[100];
          memset(a, !0, sizeof(a));
      }
      MyClass mc;
      std::cout &lt;&lt; "mc.mFirst: " &lt;&lt; mc.mFirst &lt;&lt; std::endl;
      std::cout &lt;&lt; "mc.mSecond: " &lt;&lt; mc.mSecond &lt;&lt; std::endl;
  
      int a;
      std::cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>However, the output stays the same:</p>
  
  <pre><code>mc.mFirst: 0
  mc.mSecond: 0
  a: 0
  </code></pre>
  
  <p>Can anyone explain why?</p>
  
  <h3>Update 2</h3>
  
  <p>Ok I figured it out. GCC was probably optimizing away unused variables.</p>
  
  <p>This application shows the expected behavior:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct MyClass
  {
      MyClass() : mFirst() { }
  
      MyClass(int inFirst, int inSecond) : mFirst(inFirst), mSecond(inSecond) { }
  
      int mFirst;
      int mSecond;
  };
  
  
  int main()
  {
      // Fill the stack with non-zeroes
      // Use volatile to prevent GCC optimizations.
      {
          volatile MyClass mc(1, 2);
          volatile int a = 3;
      }
  
      {
          volatile MyClass mc;
          volatile int a;
  
          std::cout &lt;&lt; "mc.mFirst: " &lt;&lt; mc.mFirst &lt;&lt; std::endl;
          std::cout &lt;&lt; "mc.mSecond: " &lt;&lt; mc.mSecond &lt;&lt; std::endl;
          std::cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; std::endl;
      }
      return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>$ g++ -o test main.cpp
  $ ./test 
  mc.mFirst: 0
  mc.mSecond: 2
  a: 3
  </code></pre>