The
#pragma pack(x) preprocessor statement forces a particular alignment/packing of structures. So x is the value for the alignment. For this reason
#pragma pack(1) has no padding because the alignment is based on a single byte. Keep in mind that some "clean" alignment are useful when you have a memory mapped interface to a piece of hardware and need to be able to control exactly where the different structure members point. However reduced padding is notably not a good speed optimization since most machines are much faster at dealing with aligned data - and as we said previously, some compilers deal with the alignment differently. Briefly, we can state :
Why do you have to use it ? To reduce the memory of the structure.
Why should you not use it ? This may lead to performance penalty because some systems work better on aligned data. Also some machines will fail to read unaligned data. Code is not always portable...
1 2 3 4 5 6 7
|
__declspec(align(4)) struct test4 {
long d; // 4 bytes
int i; // 4 bytes
short s; // 2 bytes |
char c; // 1 byte |
// padding |
};
| |
I would like to add some explanation about
__declspec(align(x)) which helped me to understand how an alignment of structure works. Using the previous example, the structure has a 4 bytes alignment. Finally there is a free space at the end (one byte). Then sizeof() gives me as output 12 (4 bytes for the long value, 4 bytes for the integer, 2 for the short value, one byte for the char (I got a padding at the end - just one byte = 12). Add another short value (2 bytes), and you have as sizeof() output 16 because the compiler adds another memory allocation. So we have now as sizeof() output 16 including three messy bytes for padding.
1 2 3 4 5 6 7 8 9
|
__declspec(align(4)) struct test4 {
long d; // 4 bytes
int i; // 4 bytes
short s; // 2 bytes |
char c; // 1 byte |
// padding | one byte
short o; // 2 bytes #
// padding # two bytes
};
| |
Acting this way, I can set the padding at the end (not really important in this context), but it is clean :)
1 2 3 4 5 6 7 8
|
__declspec(align(4)) struct test4 {
long d; // 4 bytes
int i; // 4 bytes
short s; // 2 bytes #
short o; // 2 bytes #
char c; // 1 byte |
// padding | 3 bytes
};
| |