Search code examples
for-loopverilogsequential

In Verilog, when using a for-loop within a sequential process, how can you increment the sequential variable?


Here is a snippet of code, hopefully you are alright without the preamble:

   always @ (posedge clk)
   begin
      if(rst)
      begin
         i<=0;
         j<=0;
      end
      else
      begin
         for(j = 0 ; j < 16 ; j = j+1)
         begin
            if(i<8)
            begin
               var[j] <= var_2[i];
               i <= i+1;
            end
         end      
      end
   end

Basically, I am wondering if the outer "for-loop" will erroneously increment the counter variable i, rather than simply calculating the 16 vars in parallel. If this is the case, should I cut the for-loop short so that the variable is incremented outside the for-loop?

Thanks!


Solution

  • You are making the code unnecessary complex.

    If i<8 then these get executed:

    var[j] <= var_2[i];
    i <= i+1;
    

    But the i is not incremented until after the clock edge. As 'i' does not change the condition does not change and thus once true it stays true for all values of j.

    Probably a better way of understanding this is to write the code as follows which has the exact same behavior:

       always @ (posedge clk)
       begin
          if(rst)
          begin
             i<=0;
             j<=0;
          end
          else
          begin
             for (j = 0 ; j < 16 ; j = j+1)
             begin
                if(i<8)
                   var[j] <= var_2[i];
             end      
             // i increment independent from the 'j' loop
             if(i<8)
                i <= i+1;
          end
       end