Like other variables, structure variables can be accessed by name. You can access fields within structure variables with this syntax:
variable.field
In MASM 6.0, references to fields must always be fully qualified, with both the structure or union name and the dot operator preceding the field name. Also, in MASM 6.0, the dot operator can be used only with structure fields, not as an alternative to the plus operator; nor can the plus operator be used as an alternative to the dot operator.
This example shows several ways to reference the fields of a structure called date.
DATE STRUCT ; Defines structure type
month BYTE ?
day BYTE ?
year WORD ?
DATE ENDS
yesterday DATE {9, 30, 1987} ; Declare structure
; variable
.
.
.
mov al, yesterday.day ; Use structure variables
mov bx, OFFSET yesterday ; Load structure address
mov al, (DATE PTR [bx]).month ; Use as indirect operand
mov al, [bx].date.month ; This is necessary if
; month were already a
; field in a different
; structure
Under OPTION M510 or OPTION OLDSTRUCTS, unique structure names do not need to be qualified. See Section 1.3.2 for information on the OPTION directive.
If the NONUNIQUE keyword appears in a structure definition, all fields of the structure must be fully qualified when referenced, even if the OPTION OLDSTRUCTS directive appears in the code. Also, in MASM 6.0, all references to a field must be qualified.
Even if the initialized union is the size of a WORD or DWORD, members of structures or unions are accessible only through the field's names.
In the following example, the two MOV statements show how you can access the elements of an array of structures.
WB UNION
w WORD ?
b BYTE ?
WB ENDS
array WB (100 / SIZEOF WB) DUP ({0})
mov array[12].w, 40
mov array[32].b, 2
The WB union cannot be used directly as a WORD variable. However, you can define a union containing both the structure and a WORD variable and access either field. (The next section discusses nested structures and unions.)
You can use unions to access the same data in more than one form. For example, one application of structures and unions is to simplify the task of reinitializing a far pointer. If you have a far pointer declared as
FPWORD TYPEDEF FAR PTR WORD
.DATA
BoxB FPWORD ?
BoxA FPWORD ?
BoxB2 uptr < >
you must follow these steps to point BoxB to BoxA:
mov bx, OFFSET BoxA
mov WORD PTR BoxB[2], ds
mov WORD PTR BoxB, bx
When you do this, you must remember whether the segment or the offset is stored first. However, if your program contains this union:
uptr UNION
dwptr FPWORD 0
STRUCT
offs WORD 0
segm WORD 0
ENDS
uptr ENDS
you can initialize a far pointer with these steps:
mov BoxB2.segm, ds
mov BoxB2.offs, bx
lds si, BoxB2.dwptr
This code moves the segment and the offset into the pointer and then moves the pointer into a register with the other field of the union. Although this technique does not reduce the code size, it avoids confusion about the order for loading the segment and offset.