What is the difference between packed structure and union in system verilog?

what is the difference between packed structure and union in system verilog?

In reply to lalithjithan:

The difference is they are defined in different sections of the LRM.

7.2.1 Packed structures
7.3.1 Packed unions

Understanding LRM idioms can be a bit difficult if you’ve just started reading it. Main difference between structure and union is that,

  • Structure consists of different fields which can be accessed by their names. And storage is allocated for each of these fields.
  • Whereas in Union there’s only single storage which is maximum of storage that a field can require to store data. And this common area can be accessed as any of the field name, if done carefully.

Concept of packed structure/ packed union deals with efficient memory allocation and does not change inherent behavior of struct/union data types.

You’ll also find lot of details on structure and union if you remove search word “SystemVerilog” from it! This is same across all different language.

In reply to MayurKubavat:
Excuse my terse response. I think it is very inefficient trying to learn a language by asking about one construct at a time. People should search for some examples, try creating some of their own, and then ask more directed questions.

Packed structures and unions give you multiple ways to access groups of bits in a vector ( a packed array of bits). It is not about memory allocation. For example suppose you had a 32-bit representation of single precision floating point number. You could declare that as

bit [31:0] float;

And then refer to
float[31]
as the sign,
float[30:23]
as the exponent, and
float[22:0]
as the exponent. A packed struct would let you name the fields instead of using bit ranges

typedef struct packed {bit sign; bit [7:0] exponent; bit 22:0] fraction;} single_prec_float_t;
single_prec_float_t float.

Now you can refer to
float.exponent
instead trying to remember the specific bits
float[30:23]
. You could still refer to individual bits of float if you wanted to.

Now suppose you had a 128-bit bus that you wanted to access by 8-bit bytes as well as 32-bit words. You can use a packed union

typedef union packed {
       bit [7:0] word8[8];
       bit [31:0] word32[4];
      } word128_t;