0

I have read other posts as well as the Microsoft Docs regarding the effect of #pragma pack(). I understand that it is useful when byte alignment is necessary. However, I am still unsure of the effect of putting #pragma pack() both before and after your struct. I will include an arbitrary, example struct below for clarity.

#pragma pack(1)
typedef struct
{
int var1;
int var2;
int var3;
char var4;
double var5;
} myStruct;
#pragma pack()

I would like to know if it is necessary and what effect the #pragma pack() at the last line does. I understand what #pragma pack(1) at the first line does already. Thank you.

As stated, I have already viewed other posts on this site as well as the Microsoft Docs and was not able to find an answer about the second #pragma pack() following the struct.

  • `#pragma pack()` is defaulting to 8 according to the MS docs you refered to. – wohlstad Oct 25 '22 at 16:17
  • ... and it is required because the scope of #pragma pack is by default till the end of the translation unit. See here: https://stackoverflow.com/questions/31034906/scope-of-the-pragma-pack-directive-in-visual-studio. – wohlstad Oct 25 '22 at 16:23

1 Answers1

1

Documentation says:

Calling pack with no arguments sets n to the value set in the compiler option /Zp.

So it basically resets the settings of packing to whatever the default of current compiler invocation is. It makes only the myStruct to be laid out explicitly, and other structures defined below the pragma pack() receive whatever layout is decided by the compiler.

Maciek
  • 1,696
  • 12
  • 19
  • 1
    For completeness it should be noted that this is usually the wrong thing to call, the correct way is to use `#pragma pack(push, n)` and `#pragma pack(pop)`. – Blindy Oct 25 '22 at 16:36
  • That makes a lot of sense. I saw that section about calling pack with no arguments. I just did not realize it was a sort of reset. Thank you very much. – Moonlight Crusader Oct 25 '22 at 17:47
  • @Blindy When you say wrong, do you mean undefined behavior if done another way? Or does it explicitly cause errors if done my way? – Moonlight Crusader Oct 25 '22 at 17:47
  • 1
    I mean exactly what I said, it's wrong to assume other header files' pragma pack. It's a sure way to make code corrupt memory when include order changes. Instead, you should make your changes "transparent" by pushing the previous value before changing it, and restoring it at the end of your header file. – Blindy Oct 25 '22 at 18:41