// Offset 0, no padding // Offset 1, no padding // Offset 13, nopadding
// sizeof(S3)==14, alignment 1
// 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

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;

};

#pragma pack (push, my_new_align, 1)

struct S6 {

//

Same as S2

char

c1;

//

Offset 0, no padding

int i;

//

Offset 1, no padding

char

c2;

//

Offset 5, no padding

};

 

//

sizeof(S6)==6, alignment 1

#pragma

pack

2

 

#pragma

pack

show // compiler diagnostic

 

 

 

// that shows current

 

 

 

// pragma pack setting

struct S7 {

 

 

char

c1; // Offset 0, 1 byte padding

int i;

// Offset 2, no padding

char

c2; // Offset 6, 1 byte padding

};

 

//

sizeof(S7)==8, alignment 2

#pragma

pack

(pop, my_new_align)

struct S8

{

// Same as S1

char

c1;

//

Offset 0, 3 bytes padding

int i;

//

Offset 4, no padding

char

c2;

//

Offset 8, 3 bytes padding

};

 

//

sizeof(S8)==12, alignment 4

The pack pragma may be useful when porting code between different architectures where data type alignment and storage differences are of concern. Refer to the following examples:

Data Alignment Pragmas 99

Page 99
Image 99
HP C/aC++ for PA-RISC Software manual Data Alignment Pragmas