2

I'm having some problems with for-loop statement in verilog.

reg [31:0] i;

initial begin
  for (i=2; i > 0; i = i - 1) begin
    $display ("%d\n", i);
  end
end

This code runs without any problem, but if I change the middle condition to i >= 0, the program runs repeatedly without no hope of stopping.

I don't understand why this happen!

PS: The full code can be found here: http://pastebin.com/3LX0Mkg0

1
  • 5
    Is i being interpreted as an unsigned number? In this case, 0-1=2^32-1 > 0 which would explain the infinite loop. Commented Mar 11, 2014 at 5:09

1 Answer 1

6

Eric gave the answer in a comment, so I am copying it here as an answer:

In verilog reg [31:0] i; is interpreted as an unsigned number. Therefore i >= 0 will always be true. In order to define i as signed you have to define it like this: reg signed [31:0] i;

While we are talking about signed numbers in verilog I want to point out a major gotcha: if you do a part select of a signed number (like i[15:0]) the result is unsigned. This is the case even if you select all of the bits like i[31:0]. You can fix this using the $signed task like this: $signed(i[15:0])

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.