Reputation: 1660
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:
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:
Why is the 2nd loop not working and first loop keep repeating?
Upvotes: 0
Views: 643
Reputation: 39356
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:
i
starts at 0i<=3
becomes falsei
by oneThe 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.
Upvotes: 2