Every data type has an alignment associated with it which is mandated by the processor architecture rather than the language itself. Aligning data elements allows the processor to fetch data from memory in an efficient manner and thereby improves performance. The compiler tries to maintain these alignments for data elements to provide optimal performance. How can we change it?
Windows provide pack directive to set the alignment for structure, union, and class members.
1. #pragma pack(n) – Sets the new alignment.
2. #pragma pack(push)- Pushes the current alignment setting on an internal stack
3. #pragma pack(pop)- Restores the alignment setting to the one saved at the top of the internal stack
struct Struct1 { char a; int b; char c; }; //pushes the current alignment setting on an internal stack #pragma pack(push) #pragma pack(1) //sets the alignment struct Struct2 { char a; int b; char c; }; #pragma pack(pop) //restores the alignment struct Struct3 { char a; int b; char c; }; #pragma pack(push) //pushes the current alignment #pragma pack(2) //sets the alignment struct Struct4 { char a; int b; char c; }; #pragma pack(pop) //restores the alignment int _tmain(int argc, _TCHAR* argv[]) { /*| 1 | 2 | 3 | 4 | | a(1) | pad.................. | | b(1) | b(2) | b(3) | b(4) | | c(1) | pad.................. | */ int nSizeWithDefaultPadding = sizeof(Struct1); //12 /*| 1 | | a(1) | | b(1) | | b(2) | | b(3) | | b(4) | | c(1) | */ int nSizeWithPadding1 = sizeof(Struct2);//6 int nSizeAfterRestored = sizeof(Struct3 );//12 /*| 1 | 2 | | a(1) | pad | | b(1) | b(2) | | b(3) | b(4) | | c(1) | pad | */ int nSizeWithPadding2 = sizeof(Struct4);//8 return 0; }
In Visual Studio 2015 and later we can use the standard alignas and alignof operators for same.