Does pragmapack() in C programming have any usage apart from structure packing?

81 Views Asked by At

While I'm on an interview the interviewer asked me are there any other usage of pragmapack() in C apart from structure packing? So I answered that I don't know apart from structure packing. So are there any other usage of it?

1

There are 1 best solutions below

0
On
#pragma pack(size)

is a preprocessor directive used for altering structure padding schemes. Usually a structure adds padding bytes between it's members to speed up the memory fetch operations. the number of padding bytes it used is depends on machine architecture. for example,

struct sample {
    int a;
    char b;
    int c;
};

When we see the above structure it requires only 9 bytes ( 4 + 1 + 4) to hold members a, b and c, but for a 32 bit architecture, a variable of this structure takes 16 bytes (4 + 4 + 4) of memory. even though char b only requires 1 byte, it takes 4 bytes 1 for storing value of b and other three as padding bytes.

padding_size = (word_size of machine architecture > highest sized structure member datatype's size) ? highest sized structure member datatype's size : word_size of machine architecture;

we can forcefully assign padding size using preprocessor directive #pragma pack(size) , size should be a power of 2 less than the word_size of machine architecture.

If we use like

#pragma pack(1)

for the above structure then the total amount of memory required for holding a variable of type struct sample will be (4 + 1 + 4) 9 bytes.