Search code examples
loopsverilogvariable-names

Can loop variables be used multiple times in Verilog?


I have two arrays that look like this:

reg [3:0] foo [31:0];
reg [7:0] bar [63:0];

They need to be initialized in an always block as follows:

integer i;
integer j;
always @(posedge clk) begin
  if(reset) begin
    for(i=0; i<32; i=i+1) foo[i] <= 4'h0;
    for(j=0; j<64; j=j+1) bar[j] <= 8'h0;
  end
end

As I understand it, the synthesizer will expand each loop at compilation time, which means that i and j do not actually get synthesized. Is it therefore true that I can use the same loop variable name for every loop in my code? For example, is the following code valid?

integer k;
always @(posedge clk) begin
  if(reset) begin
    for(k=0; k<32; k=k+1) foo[k] <= 4'h0;
    for(k=0; k<64; k=k+1) bar[k] <= 8'h0;
  end
end

Similarly, is the answer also true for genvar variables?

This question is about Verilog, not SystemVerilog.

Thanks in advance!


Solution

  • This question is not specific to for loops. Within any procedural block of code, if you write to a variable before reading it, and don't use it outside the procedural block, it gets synthesized as a temporary variable. You can do writes, followed by reads over and over. Each pairing gets treated separately.

    When using a for loop, this is essentially what happens as the for loop gets unrolled. It gets assigned a constant value, and then another.