2
\$\begingroup\$

Is it possible to write the following code using a for loop in Verilog?

i = 0: sum[0] <= data[0];
i = 1: sum[1] <= data[0] + data[1];
i = 2: sum[2] <= data[0] + data[1] + data[2];
i = 3: sum[3] <= data[0] + data[1] + data[2] + data[3];
.
.
i = 7: sum[7] <= data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7];
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can use a couple of for loops and a function:

logic [3:0] sum [8];
logic [7:0] data;

function logic [3:0] sum_data (int n);
    sum_data = data[0];
    for (int j=1; j<=n; j++) begin
        sum_data += data[j];
    end
endfunction

// ...

for (int i=0; i<8; i++) begin
    sum[i] <= sum_data(i);
end

Functions are synthesizable.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.