HP C Programmer's Guide (92434-90009)

Chapter 2 31
Storage and Alignment Comparisons
The HP_ALIGN Pragma
char bus_color;
};
#pragma HP_ALIGN POP
Variables declared of type struct string_1, are aligned according to the HPUX_WORD
alignment mode. Variables declared of type struct
car, are aligned according to the HPUX_NATURAL alignment mode. Variables declared of
type struct bus are aligned according to HPUX_WORD.
Accessing Non-Natively Aligned Data with Pointers
Be careful when using pointers to access non-natively aligned data types within structures
and unions. Alignment information is significant, as pointers may be dereferenced with
either 8-bit, 16-bit, or 32-bit machine instructions. Dereferencing a pointer with an
incompatible machine instruction usually results in a run-time error.
HP C permanently changes the size and alignment information of typedefs defined within
the scope of an HP_ALIGN pragma. It makes data objects, such as pointers, declared by
using typedefs, compatible with similar objects defined within the scope of the pragma.
For example, a pointer to an integer type declared with a typedef that is affected by the
HP_ALIGN pragma will be dereferenced safely when it points to an integer object whose
alignment is the same as that specified in the pragma.
The typedef alignment information is persistent outside the scope of the HP_ALIGN
pragma. An object declared with a typedef will have the same storage and alignment as all
other objects declared with the same typedef, regardless of the location of other HP_ALIGN
pragma statements in the program.
There is a slight performance penalty for using non-native data alignments. The compiler
generates slower but safe code for dereferencing non-natively aligned data. It generates
more efficient code for natively aligned data.
The following program generates a run-time error because a pointer that expects
word-aligned data is used to access a half-word aligned item:
#pragma HP_ALIGN HPUX_WORD
struct t1 { char a; int b;} non_native_rec;
#pragma HP_ALIGN POP
main ()
{
int i;
int *p = non_native_rec.b;
i = *p; /* assignment causes run-time bus error */
}
The following program works as expected because the pointer has the same alignment as
the structure:
#pragma HP_ALIGN HPUX_WORD
struct t1 { char a; int b;} non_native_rec;