__packed
Syntax
See Syntax for type attributes used on data objects. An exception is when the keyword is used for modifying the structure type in a struct or union declarations, see below.
Description
Use the __packed keyword to specify a data alignment of 1 for a data type. __packed can be used in two ways:
When used before the
structorunionkeyword in a structure definition, the maximum alignment of each member in the structure is set to 1, eliminating the need for gaps between the members.You can also use the
__packedkeyword with structure declarations, but it is illegal to refer to a structure type defined without the__packedkeyword using a structure declaration with the__packedkeyword.When used in any other position, it follows the syntax rules for type attributes, and affects a type in its entirety. A type with the
__packedtype attribute is the same as the type attribute without the__packedtype attribute, except that it has a data alignment of 1. Types that already have an alignment of 1 are not affected by the__packedtype attribute.
A normal pointer can be implicitly converted to a pointer to __packed, but the reverse conversion requires a cast.
Note
Accessing data types at other alignments than their natural alignment can result in code that is significantly larger and slower.
Use either __packed or #pragma pack to relax the alignment restrictions for a type and the objects defined using that type. Mixing __packed and #pragma pack might lead to unexpected behavior.
Example
/* No pad bytes in X: */
__packed struct X { char ch; int i; };
/* __packed is optional here: */
struct X * xp;
/* NOTE: no __packed: */
struct Y { char ch; int i; };
/* ERROR: Y not defined with __packed: */
__packed struct Y * yp ;
/* Member 'i' has alignment 1: */
struct Z { char ch; __packed int i; };
void Foo(struct X * xp)
{
/* Error:"int __packed *" -> "int *" not allowed: */
int * p1 = &xp->i;
/* OK: */
int __packed * p2 = &xp->i;
/* OK, char not affected */
char * p3 = &xp->ch;
}
See also
pack.