[C++]Byte Alignment (pack pragma)
keywords: C++, Byte Alignment, pack pragma
Example
Testing code:
class C1
{
char a;
char b;
int c;
};
class C2
{
char a;
int c;
char b;
};
class C3
{
char a;
char b;
int c;
void fun1() {}
};
class C4
{
char a;
char b;
int c;
virtual void fun1() {}
};
class C5
{
char a;
char b;
int c;
virtual void fun1() = 0;
};
int main(int argc, char* args[])
{
printf("C1 size:%zd\n", sizeof(C1));
printf("C2 size:%zd\n", sizeof(C2));
printf("C3 size:%zd\n", sizeof(C3));
printf("C4 size:%zd\n", sizeof(C4));
printf("C5 size:%zd\n", sizeof(C5));
}
Output(x64):
C1 size:8
C2 size:12
C3 size:8
C4 size:16
C5 size:16
Output(x86):
C1 size:8
C2 size:12
C3 size:8
C4 size:12
C5 size:12
What’s the default value in bytes used of packing.
(Optional) Specifies the value, in bytes, to be used for packing. If the compiler option /Zp isn't set for the module, the default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member is on a boundary that’s either a multiple of n, or a multiple of the size of the member, whichever is smaller.
Origin: pack pragma
https://docs.microsoft.com/en-us/cpp/preprocessor/pack?view=vs-2019
Never give up, not because you still have tomorrow to try, but because you may not have tomorrow to try.