title: For loop in always block
body: <p>I have a cache memory module that I want word addressable but have write enable signals for bytes.</p>
  
  <pre><code>always @ (posedge clk) begin
      //stuff...
      if(write) begin
          //Word accessible only
          //memData[lastInIndex][lastInOffset] &lt;= lastWriteData;
  
          //Supporting byte accessible
          if(lastWrEn[0])
              memData[lastInIndex][lastInOffset][7:0] &lt;= lastWriteData[7:0];
          if(lastWrEn[1])
              memData[lastInIndex][lastInOffset][15:8] &lt;= lastWriteData[15:8];
          if(lastWrEn[2])
              memData[lastInIndex][lastInOffset][23:16] &lt;= lastWriteData[23:16];
          if(lastWrEn[3])
              memData[lastInIndex][lastInOffset][31:24] &lt;= lastWriteData[31:24];
      end
      //more stuff...
  end
  </code></pre>
  
  <p>If I am writing a word to memory, I can specify which bytes should be ignored and which bytes should be written within each word.  I have tested this code and it simulates just fine.  I would like to parameterize how many bytes are in a word (in the 64 bit case, there are now 8 bytes per word).  Rather than just copy and paste more nearly identical lines, I was hoping to have some sort of for loop to instantiate my logic.</p>
  
  <pre><code>always @ (posedge clk) begin
      //stuff...
      if(write) begin
          //Word accessible only
          //memData[lastInIndex][lastInOffset] &lt;= lastWriteData;
  
          //Supporting byte accessible
          begin : BYTE_SELECTION_GENERATE
              integer i;
              for(i=0; i&lt;bytesPerWord; i=i+1)
                  if(lastWrEn[i])
                      memData[lastInIndex][lastInOffset][i*8+7:i*8] &lt;= lastWriteData[i*8+7:i*8];
          end
      end
      //more stuff...
  end
  </code></pre>
  
  <p>I have a parameter called <code>wordSize</code> that specifies how many bits each word contains (usually 32 or 64).  There is another parameter that is <code>parameter bytesPerWord = wordSize/8</code>.  When  I try to compile this version, I get an error that says <code>i is not a constant</code>.  I have also tried <code>genvar</code> and <code>generate</code> but those are not allowed in always blocks.  Is there a way to  generate the hardware that I want based off of a <code>bytesPerWord</code> parameter, or am I going to have to rely on an ugly string of <code>`ifdef</code> statements?</p>