title: Loop result is different when adding debug output (Heisenbug?)
body: <p>I have a loop that behaves differently if I add debug output in the loop. I wonder if this is a compiler bug, or if I by mistake rely on some undefined <code>C++</code> behavior.</p>
  
  <p>The loop reads integers from a <code>uint64_t</code> array, stores them in a temp array, and sum the entries. I expect the sum to be larger than 60 because of the data I have.</p>
  
  <p>If it is smaller than 60 (a surprise), I re-try the same loop, this time adding debug output. I would expect the same smaller-than-60 result, but now I get larger than 60.</p>
  
  <pre><code>uint64_t test[8];
  for(int i=0; i&lt;8; i++) {
      test[i] = overflow[index + i];
  }
  int temp[64];
  int count2 = 0;
  for(int j = 0; j &lt; 64; j++) {
      int cj = (int) ((test[j / 8] &gt;&gt; (8 * j)) &amp; 0xff);
      count2 += cj;
      temp[j] = cj;
  }
  if (count2 &lt; 60) {
      int count3 = 0;
      for(int j = 0; j &lt; 64; j++) {
          int cj = (int) ((test[j / 8] &gt;&gt; (8 * j)) &amp; 0xff);
          temp[j] = cj;
          ::std::cout &lt;&lt; " foo\n";
          count3 += cj;
      }
      ::std::cout &lt;&lt; "count2 " &lt;&lt; count2 &lt;&lt; " count3 " &lt;&lt; count3 &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>Example output:</p>
  
  <pre><code>foo
  ...
  foo
  count2 6 count3 62
  </code></pre>
  
  <p>The direction of the loop is irrelevant (same result if the loop goes from 0 to 63). There is only one thread. If I comment the cout in the second loop, I get e.g. <strong>"count2 4 count3 4"</strong> (some the original, unexpected case). As soon as I do any kind of cout (even "foo") in the loop, I get count2 != count3 again. I tried to make the first loop more complex (unnecessarily multiply cj by 100), but the same result.</p>
  
  <p>Compiler options in the Makefile:</p>
  
  <pre><code>OPT = -O3 -DNDEBUG -march=native
  CXXFLAGS += -fno-strict-aliasing -Wall -std=c++11 $(OPT)
  LDFLAGS = -Wall
  </code></pre>
  
  <p>The same result with LLVM and g++.</p>
  
  <p>The problem goes away with <code>"-O2"</code> (g++, didn't try LLVM).</p>