HP Fortran Programmer's Reference (September 2007)

HP Fortran statements
STRUCTURE (extension)
Chapter 10472
Once a value is assigned to a map block, all other map blocks become undefined. The reason is
that all map blocks share memory space within a union; therefore, the values of one map
block may become altered if you assign a value to a field in another map block. Consider the
following definition of a structure called struct and the declaration of a record called rec:
STRUCTURE /struct/
UNION
MAP
CHARACTER*8 :: s
END MAP
MAP
CHARACTER*1 :: c(8)
END MAP
END UNION
END STRUCTURE
RECORD /struct/ rec
If we made the following assignment to the s field:
rec.s = 'ABCDEFGH'
and then executed the next two PRINT statements:
PRINT *, rec.s
PRINT *, rec.c
the output would be:
ABCDEFGH
ABCDEFGH
Now, if we set values in the c field and display both fields again
rec.c(1) = '1'
rec.c(8) = '8'
PRINT *, rec.s
PRINT *, rec.c
the output would be:
1BCDEFG8
1BCDEFG8
Note how the s field has changed, even though it was not directly assigned any new values.
This is a result of the s and c field sharing the same storage space in the union. Although this
is valid coding—that is, it will not cause a compiler or runtime error—it may cause
unexpected results.
However, you can also use shared memory mapping to your benefit. The fact that map blocks
share space within a union makes unions useful for equivalencing data within a record. For
example, the following structure could be used to mask off individual bytes in a 4-byte word: