C++ #pragma pack
Asked Answered
F

1

8

What does the following statement actually do and what are it's effects?

#pragma pack(push,8)
Foreclosure answered 25/10, 2010 at 12:41 Comment(1)
msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspxEmigration
M
14

It pushes the current pack setting onto a stack (so that you can restore it later via pop) and then sets the alignment for struct elements to 8 bytes. Anything which is not naturally aligned to an 8 byte boundary will have padding bytes inserted before it to maintain the required alignment.

Moralist answered 25/10, 2010 at 12:44 Comment(1)
Just an addition for how to see the effects: Define a structure with some elements of different sizes (e.g. char, short, long, double). Then determine the size of the structure using sizeof. Place a pair of #pragma pack(push, n) and #pragma pack(pop) around the structure with different values for n (e.g. 1, 2, 4, 8). See how sizeof's results change. As an option, check out the change in relative addressing of the structure's elements.Fresh

© 2022 - 2024 — McMap. All rights reserved.