Menu
Coddy logo textTech

Generate Loops

Part of the RTL Design & Verification section of Coddy's Verilog journey. Lesson 13 of 38.

A generate-for loop creates repeated hardware during elaboration. Its genvar index is not a changing runtime register. Named generate blocks provide predictable hierarchical names for the created instances or assignments. The loop bounds must be elaboration-time constants.

Relevant excerpt; surrounding declarations and connections are supplied in the challenge.

genvar i;
generate
    for(i=0;i<WIDTH;i=i+1) begin: bitcell
        assign y[i] = a[i] ^ b[i];
    end
endgenerate

Every iteration elaborates a separate bit-level operation rather than consuming a clock cycle.

Use genvar with constant bounds to describe repeated structure at elaboration.

challenge icon

Challenge

Medium

Use a named generate-for loop with genvar i to instantiate one continuous assignment per bit, producing y[i] = a[i] XOR b[i]. WIDTH is positive. The locked testbench instantiates WIDTH values 1, 4 and 8, using the low bits of a and b for narrower instances. Output columns are y1, y4 and y8 in decimal.

Complete design.v and preserve its module names and ports. The locked testbench.v supplies input changes and prints the outputs after they settle. It chooses a scenario using a simulator argument such as +CASE=1; no standard input is required. Do not add printing, delays or simulation termination to the design. Expected output is one row of decimal values per observation, separated by one space and ending with a newline.

Try it yourself

module dut #(parameter WIDTH=4) (input [WIDTH-1:0] a,b, output [WIDTH-1:0] y);
    // Implement the parameterized circuit.
    assign y = 0;
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in RTL Design & Verification

Practice on your own: Online Verilog compiler