title: Where you can and cannot declare new variables in C?
body: <p>I heard (probably from a teacher) that one should declare all variables on top of the program/function, and that declaring new ones among the statements could cause problems.</p>
  
  <p>But then I was reading K&amp;R and I came across this sentence: "Declarations of variables (including initializations) may follow the left brace that introduces any compound statement, not just the one that begins a function". He follows with an example: </p>
  
  <pre><code>if (n &gt; 0){
      int i;
      for (i=0;i&lt;n;i++)
      ...
  }
  </code></pre>
  
  <p>I played a bit with the concept, and it works even with arrays. For example: </p>
  
  <pre><code>int main(){
      int x = 0 ;
  
      while (x&lt;10){
          if (x&gt;5){
              int y[x];
              y[0] = 10;
              printf("%d %d\n",y[0],y[4]);
          }
          x++;
      }
  }
  </code></pre>
  
  <p>So when exactly I am not allowed to declare variables? For example, what if my variable declaration is not right after the opening brace? Like here:</p>
  
  <pre><code>int main(){
      int x = 10;
  
      x++;
      printf("%d\n",x);
  
      int z = 6;
      printf("%d\n",z);
  }
  </code></pre>
  
  <p>Could this cause trouble depending on the program/machine? </p>