HP Fortran Programmer's Reference (September 2007)

HP Fortran statements
STRUCTURE (extension)
Chapter 10 471
A type declaration statement
Another nested structure
A nested record
A union definition
Note that a structure definition allows multiple levels of nesting.
For programmers who are familiar with C or Pascal, HP Fortran unions are similar to unions
in C and variant records in Pascal. HP Fortran unions differ from C unions in that they must
be defined inside a structure definition.
The structure below contains a union with two map blocks. The first contains the integer field
int; the second contains the real field float.
STRUCTURE /var/
INTEGER :: type ! 1=INTEGER, 2=REAL
UNION
MAP
INTEGER :: int
END MAP
MAP
REAL :: float
END MAP
END UNION
END STRUCTURE
To declare a record of this structure named v, use the following RECORD statement:
RECORD /var/ v
The declaration of the record v reserves 8 bytes of storage: 4 bytes for the type field and 4
bytes to be shared by int and float. If you use the int field to access the 4 bytes, they will be
interpreted as an integer; if you use the float field, they will be interpreted as a real.
It is the programmer’s responsibility to ensure that appropriate values are assigned to each
field in a union. For instance, given the previous declaration of v, the following assignments
make sense:
v.type =1 ! set the type to integer
! access the storage shared by 'int' and 'float' as an integer
v.int = 3
In contrast, the following code would yield unexpected results, although it would compile
without errors:
v.type = 1 ! set the type to integer
! the next statement contradicts the previous statement
v.float = 3.14