// Offset 0, 3 bytes padding // Offset 4, no padding
// Offset 16, 3 bytes padding // sizeof(S3)==20, alignment 4
// Offset 0, no padding // Offset 1, no padding // Offset 7, no padding
// sizeof(S4)==8, alignment 1
// Same as S1
// Offset 0, 3 bytes padding // Offset 4, no padding
// Offset 8, 3 bytes padding // sizeof(S5)==12, alignment 4

Basic Example

The following example illustrates the pack pragma and shows that it has no effect on class fields unless the class itself was defined under the pragma:

struct

S1 {

 

char

c1;

// Offset 0, 3 bytes padding

int

i;

// Offset 4, no padding

char

c2;

// Offset 8, 3 bytes padding

};

 

 

// sizeof(S1)==12, alignment 4

#pragma

pack 1

 

struct

S2 {

 

char

c1;

// Offset 0, no padding

int

i;

// Offset 1, no padding

char

c2;

// Offset 5, no padding

};

 

 

// sizeof(S2)==6, alignment 1

//S3 and S4 show that the pragma does not affect class fields

//unless the class itself was defined under the pragma. struct S3 {

char c1; S1 s; char c2;

};

struct S4 { char c1; S2 s; char c2;

};

#pragma pack

struct S5 { char c1; int i; char c2;

};

Template Example

If the pragma is applied to a class template, every instantiation of that class is influenced by the pragma value in effect when the template was defined. For example:

#pragma pack 1

template<class T> struct ST1 {

char c1;

T x;

 

 

char

c2;

 

};

 

 

#pragma

pack

 

ST1<int> obj;

// Same layout as S2 in the prior example

template <>

// Explicit specialization

struct ST1<void> {

 

char

c1;

 

char

c2;

 

};

 

// Undefined (unsupported) behavior

 

 

// ST1 was defined under a #pragma pack 1 directive

100 Pragma Directives and Attributes