0

I have the following code in verilog to test a For loop:

module test1;

reg [2:0] i;

initial
begin
    for(i=0;i<=3;i=i+1) begin
         #10;
         $display("%d",i);
    end
end

endmodule

The printed output shows:

0 1 2 3

Which makes sense to me. But the waveform below confuses me:

enter image description here

How does the reg 'i' take the value '4' here?

This is part of a bigger code I am working on where I have many nested for loops used in a testbench.

I am adding a nested loop which behaves weird:

module test1;

reg signed [2:0] i,j;

initial
begin
    for(i=-3;i<=3;i=i+1) begin
        for(j=-3;j<=3;j=j+1) begin
            #10;
            $display("%d   %d",i,j);
        end
    end
end

endmodule

The output waveform is shown below: enter image description here

Why is the 2nd loop not working and first loop keep repeating?

1 Answer 1

2

This has to do with how for loops know when to stop.

When you write

for(i=0;i<=3;i=i+1)

this says three things:

  1. i starts at 0
  2. The loop continues until i<=3 becomes false
  3. Each time, increment i by one

The thing is, i<=3 can't become false until i becomes 4. When i becomes 4, the loop stops looping. But i is still 4.


In your nested loop example, the problem is overflow.

You have declared j as signed three bits:

reg signed [2:0] i,j;

But you are looping until j becomes 4:

for(j=-3;j<=3;j=j+1)

There is no way to represent 4 as a signed three bit integer. Because j<=3 must always be true, the loop can never stop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.