Question regarding latch behaviour

Hi Forum members

I had a question regarding inferred latches in the design

If i have a code that counts the number of ones in a binary data sequence and I do

logic [31:0] sum;

always_comb begin

sum  =0;

for(int i=0;i<DATA_WIDTH;i=i+1) begin

  if(din[i])

    sum = sum + din[i];

end

end

assign dout = sum;

Would a latch be inferred for sum for the case when din[i] !=1? Since sum is intended to hold its value till the loop runs through all the bits, should I use always_latch and sum <= sum + din[i] instead?

Thank you

No, the code will not simulate as a latch when any din[i] bit is not 1. The always_comb block is triggered every time any bit in din[DATA_WIDTH-1 : 1] changes. Since you did not show us the declaration of the din signal or the value of DATA_WIDTH, we have to assume DATA_WIDTH is a parameter and din has at least that many bits.

In the first statement inside the block, you assign all bits of sum to 0. Therefore, sum does not retain state from any previous change in din. Therefore, the code simulates as combinational logic, as desired.

You should not use always_latch unless you want code to simulate as a latch.