9

What is the scope of the #pragma pack alignment in Visual C++? The API reference https://msdn.microsoft.com/en-us/library/vstudio/2e70t5y1%28v=vs.120%29.aspx says:

pack takes effect at the first struct, union, or class declaration after the pragma is seen

So as a consequence for the following code:

#include <iostream>

#pragma pack(push, 1)

struct FirstExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};

struct SecondExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};


void main()
{
   printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
   printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}

I've expected:

Size of the FirstExample is 5
Size of the SecondExample is 8

but I've received:

Size of the FirstExample is 5
Size of the SecondExample is 5

That is why I am a little surprised and I really appreciate any explanation you can provide.

rgb
  • 1,750
  • 1
  • 20
  • 35
  • 1
    Both of your structures are located after the pragma in the file. I'd be surprised if they're different. Your output shows two 'FirstExample' lines so it doesn't match your source code... – Jay Jun 24 '15 at 19:16
  • @Jay Thanks for your comment. I've corrected this mistake. – rgb Jun 24 '15 at 19:25

3 Answers3

9

Just because it "takes effect at the first struct" does not mean that its effect is limited to that first struct. #pragma pack works in a typical way for a preprocessor directive: it lasts "indefinitely" from the point of activation, ignoring any language-level scopes, i.e. its effect spreads to the end of translation unit (or until overridden by another #pragma pack).

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
6

It takes effect at the first struct, union, or class declaration after the pragma is seen and lasts until the first encountered #pragma pack(pop) or another #pragma pack(push) which last to its pop-counterpart.

(push and pops usually come in pairs)

engf-010
  • 3,980
  • 1
  • 14
  • 25
4

You should call #pragma pack(pop) before SecondExample

#include <iostream>
#pragma pack(push, 1)

struct FirstExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};

#pragma pack(pop)

struct SecondExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};


void main()
{
 printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
 printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}
JamesWebbTelescopeAlien
  • 3,547
  • 2
  • 30
  • 51