# Verilog For Loop in simulation and when synthesized

Status
Not open for further replies.

#### madushan

##### Newbie level 4
Hi,
I have a question regarding how verilog for loops work when synthesized

assume this code

reg [7 : 0] array = 2'b10101010;
reg found = 0;
integer j = 0;
integer i;

always @ (posedge clk) begin
for (i = 0; i < 8; i = i + 1) begin
if (array) begin
if (!found) begin
j <= i;
found <= 1'b1;
end
end
end
end

please consider the execution for only 1 clock cycle,
what will be the value of j after 1 clock cycle?
I think in the synthesized circuit, the value will be a garbage,
in the simulation the value of j will be 1

Did I get this correctly?

Please explain
Thanks

#### dave_59

##### Advanced Member level 3
You need to initialize j and found before you enter the for loop, bot as part of the variable declaration. Otherwise they will look like latches. Also use a blocking assignment to assign to found, it is really just local to the always block.

#### madushan

##### Newbie level 4
I know, this j and found should be initialized in a reset block, or initial block, but that's not the point.
As I know blocking or non blocking statements, both work as non blocking statements when synthesized, this blocking statements only work in sequence in simulation only as per my knowledge

- - - Updated - - -

Hi, Dave from Mentor Graphics,
I ran a simulation for the following code

Code:
module core(
input clk,
input reset
);

integer i, state, k, j;

always @ (posedge clk) begin
if (reset) begin
state <= 0;
i <= 0;
end
else begin
if (state == 0) begin
if (1) begin
i <= 9;
end
if (1) begin
i <= 10;
end
state <= 1;
end
end
end

endmodule
Questa Advanced Simulator 10.1.c gave me the answer for i as 10, is this really correct hardware behavior? I when synthesized this, i value will be a garbage

#### std_match

##### Advanced Member level 4
The whole point with Verilog and VHDL is that a simulation should give the same result as the real circuit.
It is possible to get a mismatch, but not with your examples.
The whole "always" block is executed every clock cycle. In the synthesized hardware, this is achieved by using parallel hardware.
The code in your first post describes a "priority encoder" and j get the final value every clock cycle.
There is no loop in the synthesized logic, just combinatorial logic that directly produces the final value.

#### dave_59

##### Advanced Member level 3
In fact, a common synthesis coding style is to assign default values to signals to prevent latches from being created, and then conditionally assign another value
Code:
begin
sig = 0;
if (expr1)  sig = expr2;
end

Status
Not open for further replies.