Search code examples
verilogsystem-verilog

How to simplify code using a temporal int variable


I want CODE 1 and CODE 2 to do the same

module testModule #(    parameter LEN = 4,
                        parameter logic [0:0] OPTION = 1'b0 )
(
    input                         Clk,
    input         [ 7:0][LEN-1:0] DataIn,
    input         [ 7:0][LEN-1:0] Factor,
    output        [15:0][LEN-1:0] DataOut_1,
    output        [15:0][LEN-1:0] DataOut_2
);

    // CODE 1
    always_ff @(posedge Clk) begin
        for (int i = 0; i < LEN; i++) begin
            if (OPTION == 1'b0) begin
                DataOut_1[i] <= DataIn[i] * Factor[0];
            end else begin
                DataOut_1[i] <= DataIn[i] * Factor[i];
            end
        end
    end

    // CODE 2
    always_ff @(posedge Clk) begin
        for (int i = 0; i < LEN; i++) begin
            int select = (OPTION == 1'b0) ? 0 : i;
            DataOut_2[i] <= DataIn[i] * Factor[select];
        end
    end

endmodule

OPTION can be either 0 of 1.

But I get the following errors in CODE 2 in line int select = (OPTION == 1'b0) ? 0 : i;

Local static variable with initializer requires 'static' keyword

automatic variable illegal in static variable initializer

I don't want to simplify the for loop because the in my original code I need it

This question is a variant on this other but I didn't want to change the original code question


Solution

  • You have a couple of issues there:

    1. you cannot assign to a net inside an always block. DataOut_1/2 are declared as nets. So, you should declare them as regs at minimum:
        output        reg [15:0][LEN-1:0] DataOut_1,
        output        reg [15:0][LEN-1:0] DataOut_2
    
    1. All variables defined in the module are static by nature. Except in some cases. The i defined in the 'for' loop is automatic. Therefore you cannot use it as an initializer to a static variable. You need to declare 'select' as automatic:
    automatic int select = (OPTION == 1'b0) ? 0 : i;