Search code examples
verilogsystem-veriloghdl

Verilog/SV conditional variable definition


Is there a way to manipulate variable instantiation depending on a parameter?

For example, here if I were to put just bit [WIDTH-1:0] a; and set DEPTH == 1, WIDTH would be 0 and bit [-1:0] a; would not make sense.

When I code it like in the example below I get an error on the second $display: "Undeclared identifier: a". Is there a way to achieve this in Verilog/SV or is there an error in my code?

module test #(
  parameter DEPTH = 2,
  parameter WIDTH = $clog2(DEPTH)
)();

  generate
    if (WIDTH == 0) begin
      bit             a;
    end else begin
      bit [WIDTH-1:0] a;
    end
  endgenerate

  initial begin
    $display("WIDTH: %d", WIDTH);
    $display("Bit width of a: %d", $bits(a));
  end
endmodule: test

Solution

  • All you need to do is

    bit [(WIDTH>0 ? WIDTH-1 : 0):0] a;