Aggregates and Unions

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Aggregates and Unions.

Other types such as arrays, structs, and unions have stricter alignment requirements that ensure consistent aggregate and union storage and data retrieval. Here are the definitions for array, structure, and union:

Array
Contains an ordered group of adjacent data objects. Each object is called an element. All elements within an array have the same size and data type.

Structure
Contains an ordered group of data objects. Unlike the elements of an array, the data objects within a structure can have different data types and sizes. Each data object in a structure is called a member.

Union
An object that holds any one of a set of named members. The members of the named set can be of any type. The storage allocated for a union is equal to the storage required for the largest member of that union, plus any padding required for alignment.

The following table shows the strongly suggested alignment for the scalar members of unions and structures.

Scalar TypeC Data TypeRequired Alignment
INT8charByte
UINT8unsigned charByte
INT16shortWord
UINT16unsigned shortWord
INT32int, longDoubleword
UINT32unsigned int, unsigned longDoubleword
INT64__int64Quadword
UINT64unsigned __int64Quadword
FP32 (single precision)floatDoubleword
FP64 (double precision)doubleQuadword
POINTER*Quadword
__m64struct __m64Quadword
__m128struct __m128Octaword

The following aggregate alignment rules apply:

  • The alignment of an array is the same as the alignment of one of the elements of the array.

  • The alignment of the beginning of a structure or a union is the maximum alignment of any individual member. Each member within the structure or union must be placed at its proper alignment as defined in the previous table, which may require implicit internal padding, depending on the previous member.

  • Structure size must be an integral multiple of its alignment, which may require padding after the last member. Since structures and unions can be grouped in arrays, each array element of a structure or union must begin and end at the proper alignment previously determined.

  • It is possible to align data in such a way as to be greater than the alignment requirements as long as the previous rules are maintained.

  • An individual compiler may adjust the packing of a structure for size reasons. For example /Zp (Struct Member Alignment) allows for adjusting the packing of structures.

Types and Storage

Show: