Scope of the pragma pack directive in Visual Studio

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

a package takes effect on the first declaration of a struct, union, or class after viewing the pragma

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 expected:

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

but i got:

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

That's why I'm a little surprised, and I really appreciate any explanation you can provide.

+7
c ++ visual-studio-2013 preprocessor-directive
source share
3 answers

Just because it โ€œtakes effect at the first structureโ€ does not mean that its effect is limited to this first structure. #pragma pack works in a typical way for the preprocessor directive: it lasts "infinitely" from the activation point, ignoring any areas of the language level, i.e. its effect extends to the end of the translation unit (or until overridden by another #pragma pack ).

+5
source share

It takes effect on the first declaration of a struct, union, or class after the pragma is visible and continues until the first #pragma (pop) package or another #pragma (push) package is the last for its pop-duppart .

(push and pops usually fall in pairs)

+4
source share

You must 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)); } 
+2
source share

All Articles