cstructpragmapragma-pack

What is the effect of #pragma pack() when it follows a struct definition?


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.


Solution

  • 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.