How to initialize unpacked array of unpacked union of unpacked structs?

Viewed 29

What is the legal method of initializing this?

module tb();
typedef struct {
    logic [3:0] A;
} a_t;
typedef struct {
    logic [7:0] B;
} b_t;
typedef union {
    a_t a;
    b_t b;
} a_b_t;
a_b_t a_b [8];
initial begin
    a_b <= '{default: '{default: 0}};
end
endmodule

xrun gives this error:

xmelab: *E,APBLHS (./tmp.sv,14|23): Assignment pattern - LHS must be an array or structure [SystemVerilog].

I've tried a variety of other ways, and I can't quite get this right. I'm working around it right now by initializing each entry separately with 2 lines of initialization.

1 Answers

As the error message state, assignment patterns only work with struct and arrays, not unions. You would need to use a foreach loop to assign each union member.

initial 
  foreach (a_b[i]) begin
    a_b[i].a <= '{default:0};
    a_b[i].b <= '{default:0};
end

Note that unless you are using the DPI for C compatibility, unpacked unions have little usefulness in SystemVerilog. Use packed unions instead.

Related