# Pragma pack (2) meaning and usage

Source: Internet
Author: User

# Pragma pack (n) tells the compiler that the byte alignment mode is n Bytes alignment. n Bytes alignment means that there are two types of offsets for the starting address of the variable: first, if n is greater than or equal to the number of bytes occupied by the variable, the offset must satisfy the default alignment. Second, if n is less than the number of bytes occupied by the type of the variable, if the offset is a multiple of N, the default alignment is not required. The total size of the structure also has a constraint, which is divided into the following two cases: if n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be a multiple of the space occupied by the largest variable; otherwise, it must be a multiple of N.

For example

# Pragma pack (2)

Union u
{
Char Buf [13];
Int I;
};
Enum color {red, blue, yellow };

Struct t
{
Int I;
Union u;
Color C;
};


Sizeof (struct T) = 22

If # pragma pack (4), sizeof (struct T) = 24.

You can also use push and pop for default recovery.

# Pragma pack (push)

# Pragma pack (2)

...

# Pragma pack (POP)


Note: Generally, N takes only 1, 2, 4, and so on. the compiler should automatically convert n to a value close to the above value.

Original article: http://blog.csdn.net/hongchangfirst/article/details/8886269

Author: hongchangfirst

Hongchangfirst home: http://blog.csdn.net/hongchangfirst

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.