C ++ # pragma pack command,
Microsoft official documentation says # The pragma pack command specifies pack alignment for structure, union, and class members. The main function is to change the memory alignment of the compiler. This command plays an important role in the processing of network packets. # pragma pack (n) is his most basic usage, the function is to change the alignment of the compiler. If this instruction is not used, the compiler uses # pragma pack (8), which is the default alignment of 8 bytes by default, the n value can be any value in (1, 2, 4, 8, 16.
To write a program:
# Include <iostream>
# Include <stddef. h>
Using namespace std;
Struct Test {
Short a; // 2
Int B; // 4
Double c; // 8
Long d; // 8
};
# Pragma pack (2)
Struct S {
Short a; // 2
Int B; // 4
Double c; // 8
Long d; // 8
};
Int main ()
{
Cout <offsetof (Test, a) <endl;
Cout <offsetof (Test, B) <endl;
Cout <offsetof (Test, c) <endl;
Cout <offsetof (Test, d) <endl;
Cout <"---------------" <endl;
Cout <offsetof (S, a) <endl;
Cout <offsetof (S, B) <endl;
Cout <offsetof (S, c) <endl;
Cout <offsetof (S, d) <endl;
System ("pause ");
Return 0;
}
The program prints the following results on a win32 PC:
0
4
8
16
---------------
0
2
6
14