Out of range assignment of a dynamic array


typedef enum {NOA, TIE_H, TIE_L} sig_type_t;
sig_type_t sig_type[8];
sig_type = new();

sig_type[0] = TIE_H; // this is OK
sig_type[7] = TIE_L; // this is fine too
sig_type[8] = TIE_H; // sig_type[8] is out of range and will get NOA instead of TIE_H

If an out of range element of a dynamic array is assigned with a value for the first time, it will not get the RHS literal value in the assignment, instead it will be initialized to 0.
So here comes the problems

  1. Why the out of range assignment/access doesn’t trigger compile time or run time error. I’ve seen the orthodox way of widen dynamic array width while preserving old elements, which is actually create a new array to overwrite existing one, so I assume SystemVerilog automatically does this for the out of range assignment?
  2. If this is true, then why SystemVerilog doesn’t just take the literal value and assign it to the new element? Rather it ignore the literal and initialize the new element to 0? This can easily create buggy code.
  3. I only run the simulation a few times, so I am not sure if the out of range value in above example actually gets a default 0, or the 0 is just randomly pulled out of memory, and it will change from sim to sim?

In reply to Changyu:

I think you meant to declare a dynamic array rather than a fixed sized array with 8 elements.

sig_type_t sig_type[]= new[8];

There is a difference in what can be checked at compile time for out-bounds indexes.

Verilog is not type safe when it comes to array index selects. A write to an out-of-range select is ignored (does not perform the write), and a read of an out-of-range select returns the default uninitialized value for the type, NOA in your example, but X for reg/logic.

This behavior makes sense as Verilog was originally developed as a Hardware Description Language as this is what happens in hardware.

The only way you can change the size of a dynamic array is by using the constructor new[N], or as a complete copy of another array as a whole.