pack
Specifies packing alignment for structure, union, and class members.
#pragma pack( [ show ] | [ push | pop ] [, identifier ] , n )
pack gives control at the data-declaration level. This differs from compiler option /Zp, which only provides module-level control. pack takes effect at the first struct, union, or class declaration after the pragma is seen; pack has no effect on definitions. Calling pack with no arguments sets n to its default value. This is equivalent to compiler option /Zp8.
Note that if you change the alignment of a structure, the structure will not use as much space in memory, but you may see a decrease in performance or even get a hardware-generated exception for unaligned access. It is possible to modify this exception behavior with SetErrorMode.
#pragma pack(pop, identifier, n) is undefined.
For more information on modifying alignment, see:
Examples of Structure Alignment (x64 specific)
The following sample shows how to the pack pragma to change the alignment of a structure.
// pragma_directives_pack.cpp
#include <stddef.h>
#include <stdio.h>
struct S {
int i; // size 4
short j; // size 2
double k; // size 8
};
#pragma pack(2)
struct T {
int i;
short j;
double k;
};
int main() {
printf("%d ", offsetof(S, i));
printf("%d ", offsetof(S, j));
printf("%d\n", offsetof(S, k));
printf("%d ", offsetof(T, i));
printf("%d ", offsetof(T, j));
printf("%d\n", offsetof(T, k));
}
0 4 8 0 4 6
The following sample shows how to use the push, pop, and show syntax.
// pragma_directives_pack_2.cpp // compile with: /W1 /c #pragma pack() // n defaults to 8; equivalent to /Zp8 #pragma pack(show) // C4810 #pragma pack(4) // n = 4 #pragma pack(show) // C4810 #pragma pack(push, r1, 16) // n = 16, pushed to stack #pragma pack(show) // C4810 #pragma pack(pop, r1, 2) // n = 2 , stack popped #pragma pack(show) // C4810