title: Is a variable declared in a loop body preserved during iterations?
body: <p>Consider a loop in C which declares a character array in the loop's body. At each iteration, a character of array is modified until the end is reached. At the end, the variable is printed. The description would expand to the next code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void) {
      int i = 0;
      for (;;) {/* same as: while(1) { */
          char x[5];
          x[i] = '0' + i;
          if (++i == 4) {
              x[i] = '\0'; /* terminate string with null byte */
              printf("%s\n", x);
              break;
          }
      }
      return 0;
  </code></pre>
  
  <p>Many may expect <code>0123</code> as output. But for some reason GCC 4.7 does not do that when compiling with optimization enabled (<code>-O1</code> and higher). It instead puts random data in the first bytes of the character array, which becomes:</p>
  
  <pre><code>| 0  |  1  |  2  |  3  |  4   |
  |     RANDOM     | '3' | '\0' |
  </code></pre>
  
  <p>I think that this is logical behaviour from the language point of view: automatic variables are gone after a block is terminated, so the above "random" behaviour should be expected.</p>
  
  <p>What should be the correct behaviour? <strong>I know that moving the declaration of <code>x</code> outside the loop "fixes" it, but that does not say anything about the behaviour of this snippet</strong>. The real-world problem is a <a href="http://bugzilla.netfilter.org/show_bug.cgi?id=774" rel="nofollow">bug in Netfilter</a>.</p>