I know that sizeof
is a compile-time calculation, but this seems odd to me: The compiler can take either a type name, or an expression (from which it deduces the type). But how do you identify a type within a class? It seems the only way is to pass an expression, which seems pretty clunky.
struct X { int x; };
int main() {
// return sizeof(X::x); // doesn't work
return sizeof(X()::x); // works, and requires X to be default-constructible
}
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes.
An alternate method works without needing a default constructor:
return sizeof(((X *)0)->x);
You can wrap this in a macro so it reads better:
#define member_sizeof(T,F) sizeof(((T *)0)->F)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With