Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't sizeof parse struct members?

Tags:

c++

sizeof

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
}
like image 966
Tom Avatar asked Jan 25 '10 00:01

Tom


People also ask

Does sizeof work on struct?

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.

What is the size of struct always?

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.

How is the size of structure determined?

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.

How many bytes is a struct in C++?

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.


1 Answers

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)
like image 181
Greg Hewgill Avatar answered Oct 24 '22 00:10

Greg Hewgill