Skip to main content

IAR Embedded Workbench for RX 5.20

__packed

In this section:
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 struct or union keyword 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 __packed keyword with structure declarations, but it is illegal to refer to a structure type defined without the __packed keyword using a structure declaration with the __packed keyword.

  • 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 __packed type attribute is the same as the type attribute without the __packed type attribute, except that it has a data alignment of 1. Types that already have an alignment of 1 are not affected by the __packed type 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.