title: Declaring variables in Verilog for loop
body: <p>I've been trying to wrap my head around how for loops are simulated and synthesized in Verilog, but there's one aspect I've noticed that I can't quite understand. It seems that when variables are declared from within a for loop, only one variable is actually created (I'm not sure if this is in the first or the last iteration of the loop), which is then &quot;shared&quot; with the rest of the loop iterations. To better convey what I'm trying to ask, consider the code below where we fill an array, <code>q</code>, with an alternating <code>01</code> pattern:</p>
  <pre><code>always @(posedge clk) begin
    int j;
    for (int i = 0; i &lt; 256; i++) begin
      j = i % 2;
      case (j)
        1 : q[i] &lt;= 1;
        default : q[i] &lt;= 0;
      endcase
    end
  end
  </code></pre>
  <p>This functions as I would expect it to (i.e., how one would expect this to work in a procedural programming language). However, when we declare <code>j</code> <em>inside</em> the for loop, <code>q</code> is filled with a constant series of <code>1</code>s--not what I was expecting.</p>
  <pre><code>always @(posedge clk) begin
    for (int i = 0; i &lt; 256; i++) begin
      int j = i % 2;
      case (j)
        1 : q[i] &lt;= 1;
        default : q[i] &lt;= 0;
      endcase
    end
  end
  </code></pre>
  <p>Logically, it would seem as though both pieces of code are describing the same behaviour, but when simulated that's not the case. So, what gives?</p>