C ++ # pragma pack command,

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.