// Compiled with MSVC 10 using "cl /W4 alignment.cpp" // this program gives on a x86-64: // // char (size 1) aligned as 1 // short (size 2) aligned as 2 // int (size 4) aligned as 4 // long long int (size 8) aligned as 8 // float (size 4) aligned as 4 // double (size 8) aligned as 8 // test1 (size 24) aligned as 8 // test2 (size 16) aligned as 8 // test3 (size 3) aligned as 1 // #include #include #define PRINT_ALIGNMENT(t) print_alignment(#t) template void print_alignment(const char *name) { std::size_t a = std::alignment_of::value; printf("% -16s (size %2d) aligned as %d\n", name, sizeof(T), a); } struct test1 { char c1; double d1; char c2; }; // Same as test1 but will most probably // take up less space due to more efficient // layout. struct test2 { double d1; char c1; char c2; }; // Demonstrates together with test1 // that structures align to the // member with the biggest alignment // requirement. struct test3 { char c1; char c2; char c3; }; int main(int argc, char *argv[]) { PRINT_ALIGNMENT(char); PRINT_ALIGNMENT(short); PRINT_ALIGNMENT(int); PRINT_ALIGNMENT(long long int); PRINT_ALIGNMENT(float); PRINT_ALIGNMENT(double); PRINT_ALIGNMENT(test1); PRINT_ALIGNMENT(test2); PRINT_ALIGNMENT(test3); }