Verilog Loops

Verilog provides several loop constructs. Understanding which are synthesizable is crucial for RTL design.

for Loop

The most common loop, synthesizable when bounds are constant:

Synthesizable for Loop
module bit_count (
    input  wire [7:0] data,
    output reg  [3:0] count  // Max 8 = fits in 4 bits
);
    integer i;
    always @(*) begin
        count = 0;
        for (i = 0; i < 8; i = i + 1) begin
            count = count + data[i];
        end
    end
endmodule

Synthesis Requirement

For synthesis, loop bounds must be compile-time constants. The loop is "unrolled" into parallel hardware.

while Loop

while loops execute as long as a condition is true:

while Loop (Testbench Only)
// Typically used in testbenches
initial begin
    integer count;
    count = 0;
    while (count < 10) begin
        $display("Count = %0d", count);
        #10;
        count = count + 1;
    end
end

Generally not synthesizable because loop count may not be known at compile time.

repeat Loop

repeat executes a fixed number of times:

repeat Loop
// Testbench: Send 5 transactions
initial begin
    repeat (5) begin
        @(posedge clk);
        data <= $random;
        valid <= 1;
        @(posedge clk);
        valid <= 0;
    end
end
// Synthesizable context: shift register
always @(posedge clk) begin
    repeat (8) begin
        shift_reg = {shift_reg[6:0], data_in};
    end
end

forever Loop

forever runs indefinitely, used for clock generation:

Clock Generation
// Testbench clock generator
reg clk;
initial begin
    clk = 0;
    forever #5 clk = ~clk;  // 10ns period (100MHz)
end
// Alternative using always
always #5 clk = ~clk;

Never synthesizable – used only in testbenches.

Synthesis Summary

Loop Synthesizable? Use Case
for (with constant bounds) Bit manipulation, array init
while ❌ Usually not Testbench only
repeat (with constant) Fixed iterations
forever ❌ Never Clock generation

Common Interview Questions

  1. Are Verilog for loops synthesizable?

    Yes, but only when the loop bounds are compile-time constants. The loop gets unrolled into parallel hardware.

  2. How do you generate a clock in a testbench?

    Use forever #period clk = ~clk; or always #period clk = ~clk;

  3. What's the difference between for and generate-for?

    for is procedural (inside always); generate-for is structural (creates module instances).