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?
-
To my knowledge it packs elements of structures, unions, and, in C++, class members. – Frankie_C Dec 05 '18 at 08:48
-
2What do you mean by "pragmapack()"? – melpomene Dec 05 '18 at 08:50
-
Did the interviewer frown? Make a note? Laugh dismissively? In other words: why would you think your answer was wrong? Did you check the documentation for your compiler? – Jongware Dec 05 '18 at 09:19
-
2Could it have been `#pragma pack`, i.e., was it a spoken question? – Arkku Dec 05 '18 at 09:25
-
1Yes. I suppose you could have followed up by explaining why non-standard structure packing might be useful. Knowledge they really want to test you on. – Hans Passant Dec 05 '18 at 09:27
1 Answers
#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.

- 564
- 2
- 21