Software & Finance





C++ - Pragma Pack Macro





Using pragma pack macro is good for storage, however it may need more Memory IO read and write cycle.

 

#pragma pack(1)

struct MyStruct1

{

    int a; // allocates 4 bytes

    char ch1; // allocates 1 byte

    int b; // allocates 4 bytes

    char ch2; // allocates 1 byte

};

 

In the above example, to read the value of b, we need two IO read cycles in 32 bit machine because of its memory alignment.

    cout << sizeof(MyStruct1); // displays 10

 

 

#pragma pack(2)

struct MyStruct2

{

    int a; // allocates 4 bytes

    char ch1; // allocates 2 byte

    int b; // allocates 4 bytes

    char ch2; // allocates 2 byte

};

 

cout << sizeof(MyStruct2); // displays 12

 

 

 

#pragma pack(4)

struct MyStruct3

{

    int a; // allocates 4 bytes

    char ch1; // allocates 4 byte

    int b; // allocates 4 bytes

    char ch2; // allocates 4 byte

};

cout << sizeof(MyStruct3); // displays 16 In the above example, to read the value of b, we need only one IO read cycles in 32 bit machine because of its memory alignment.