The disadvantage of arrays is that all the elements stored in then are to be of the same data type. If we need to use a collection of different data types, it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.
struct {
int a;
byte b;
bit [7:0] c;
} my_data_struct;
The keyword "struct" declares a structure to holds the details of four fields namely a,b and c. These are members of the structures. Each member may belong to different or same data type. The structured variables can be accessed using the variable name "my_data_struct".
my_data_struct.a = 123;
$display(" a value is %d ",my_data_struct.a);
Assignments To Struct Members:
A structure literal must have a type, which may be either explicitly indicated with a prefix or implicitly indicated by an assignment-like context.
my_data_struct = `{1234,8'b10,8'h20};
Structure literals can also use member name and value, or data type and default value.
my_data_struct = `{a:1234,default:8'h20};
Union
Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area. A union allows us to treat the same space in memory as a number of different variables. That is a Union offers a way for a section of memory to be treated as a variable of one type on one occasion and as a different variable of a different type on another occasion.
union {
int a;
byte b;
bit [7:0] c;
} my_data;
memory allocation for the above defined struct "my_data_struct".
Memory allocation for the above defined union "my_data_union".
Packed Structures:
In verilog , it is not convenient for subdividing a vector into subfield. Accessing subfield requires the index ranges.
my_data[`b_indx] = 8'b10; // writing to subfield b
$display(" %d ",my_data[`a_indx]); // reading subfield a
A packed structure is a mechanism for subdividing a vector into subfields that can be conveniently accessed as members. Consequently, a packed structure consists of bit fields, which are packed together in memory without gaps. A packed struct or union type must be declared explicitly using keyword "packed".
Memory allocation for the above defined packed struct "my_data".
One or more bits of a packed structure can be selected as if it were a packed array, assuming an [n-1:0] numbering:
My_data [15:8] // b
If all members of packed structure are 2-state, the structure as a whole is treated as a 2-state vector.
If all members of packed structure is 4-state, the structure as a whole is treated as a 4-state vector.
If there are also 2-state members, there is an implicit conversion from 4-state to 2-state when reading those members, and from 2-state to 4-state when writing them.