Electrical – Verilog for loop – genvar vs int

system-verilogverilog

When creating logic using a for loop, Verilog requires the loop index to be declared. I've seen examples where it's done with either "int" or "genvar" keywords.
For example:

// Using genvar:
for (genvar x = 0 ; x < some_value ; x++) begin
// do something with reference to x
end 

// Using int:
for (int x = 0 ; x < some_value ; x++) begin
// do something with reference to x
end 

When should I choose one over the other ?

Best Answer

This is somewhat historical. Prior to SystemVerilog, you had to declare the loop index separately, and prior to Verilog-2001, you had to enclose a generate-for loop with the keywords generate/endgenerate

module top;
  generate 
    genvar i;
    for (i=0; i<4 ; i = i + 1) begin
       integer j;
       reg [i+1:0] value;
       initial for(j=0; j<4; j = j + 1) $display("i:%0d j:%0d value:%b",i,j, value);
    end
  endgenerate
endmodule

This was to indicate that i was not an index variable, but was part of an elaboration unrolling construct. Verilog-2001 got rid of the need for the extra keywords because it could determine that the outer for-loop was a not procedural loop, and the inner for-loop was procedural.

SystemVerilog added the ability to declare the loop iteration index variable inside the for-loop, but it still requires you to use the genvar index declaration to inidicate that it is not really a variable.

module top;
    for (genvar i=0; i<4 ; i++) begin
           reg [i+1:0] value;
           initial for(int j=0; j<4; j++) $display("i:%0d j:%0d value:%b",i,j, value);
    end
endmodule
Related Topic