What\'s the difference between sizeof and alignof?
#include
#define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << \'/\' << a
Old question (although not marked as answered..) but thought this example makes the difference a bit more explicit in addition to Christian Stieber's answer. Also Meluha's answer contains an error as sizeof(S) output is 16 not 12.
// c has to occupy 8 bytes so that d (whose size is 8) starts on a 8 bytes boundary
// | 8 bytes | | 8 bytes | | 8 bytes |
struct Bad { char c; double d; int i; };
cout << alignof(Bad) << " " << sizeof(Bad) << endl; // 8 24
// | 8 bytes | | 8 bytes |
struct Good { double d; int i; char c; };
cout << alignof(Good) << " " << sizeof(Good) << endl; // 8 16
It also demonstrates that it is best ordering members by size with largest first (double in this case), as the others members are constrained by that member.