__unaligned keyword

9/7/2007

The __unaligned keyword is a type modifier in pointer definitions. It indicates to the compiler that the data pointed to might not be properly aligned on a correct address.

To be properly aligned, the address of an object must be a multiple of the size of the type. For example, two-byte objects must be aligned on even addresses.

When data is accessed through a pointer declared __unaligned, the compiler generates the additional code necessary to load or store, or read or write the data without causing alignment errors.

It is best to avoid using unaligned data, but in some cases the usage can be justified by the need to access packed structures such as shared disk structures or I/O hardware.

Note: UNALIGNED is a Win32 macro that expands to __unaligned on hardware platforms that require it. UNALIGNED expands to nothing on platforms that do not require __unaligned.

For portability, use UNALIGNED instead of the __unaligned keyword. When you use the UNALIGNED macro, include the windef.h header, as in the following example:

#include <windef.h>
int UNALIGNED *p1;               // p1 is a pointer to unaligned int
struct {int i;} UNALIGNED *p2; // p2 is a pointer to unaligned struct

See Also

Concepts

Working with Packing Structures