Randomization

Below two codes generate different values of i :

1.)


repeat(10) begin 
 int i = $urandom() ;
 display(i); 
end 

2.)


repeat(10) begin 
 int i ;
 i = $urandom() ;
 display(i); 
end

please explain why there is difference in the values of i generated by two codes ?

You didn’t describe how your results differ, but when I run your 2 code samples, I see the following differences. When I run code1, I get the same number 10 times. When I run code2, I get 10 different numbers.

When I run code1 with the Cadence Incisive simulator, I get a warning that I should declare i with the static keyword. I believe the difference in behavior is related to variable lifetime, as described in the IEEE Std 1800-2012, section “6.21 Scope and lifetime”.

If I change code1 and declare i using the automatic keyword, I get 10 different numbers:

automatic int i = $urandom() ;

In reply to withankitgarg:
It would help to show the complete context of where this repeat statement is located, as well as an example of the output you are getting versus what you expected.
Here is an example of a compete self-contained executable example for code snippet 2.)

module top;
initital
   repeat(10) begin 
                int i ;
                i = $urandom() ;
                display(i); 
              end
endmodule


In the above case, the statement
i = $urandom();
gets executed each time through the repeat loop.

To do the same for the first code snippet would actually be illegal code and should have generated a compiler error. That is because declaration of i is, by default, a static variable and its initialization only happens once at time 0. The SystemVerilog LRM requires you to explicitly declare i as either static or automatic to make sure you are aware of the initent.

module top;
initial
   repeat(10) begin 
                static int i = $urandom() ;
                display(i); 
              end
endmodule


In reply to dave_59:

could you please explain how being a static variable, int i is getting same value for all the three instances.

In reply to abhishekmj:

In reply to dave_59:
could you please explain how being a static variable, int i is getting same value for all the three instances.

Three instances of what? Please show some code.

Hi Dave ,

Thanks for your reply .

If I use class these 2 code snippets in class then this kind of error will not be there , right ?

In reply to withankitgarg:

If I use class these 2 code snippets in class then this kind of error will not be there , right ?

Correct. Variable declarations inside class methods are automatic by default.