What are the differences between:
sizeof(struct name_of_struct)
vs
sizeof(name_of_struct)
The return values of the subject are the same.
Is there any difference between the two? Even if it is subtle/not important, I'd like to know.
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.
struct name_of_struct
refers unambiguously to a struct
/class
tagged name_of_struct
whereas name_of_struct
may be a variable or a function name.
For example, in POSIX, you have both struct stat
and a function named stat
. When you want to refer to the struct type, you need the struct
keyword to disambiguate (+ plain C requires it always -- in plain C, regular identifiers live in a separate namespace from struct tags and struct tags don't leak into the regular identifier namespace like they do in C++ unless you explicitly drag them there with a typedef as in typedef struct tag{ /*...*/ } tag;
).
Example:
struct foo{ char x [256];};
void (*foo)(void);
int structsz(){ return sizeof(struct foo); } //returns 256
int ptrsz(){ return sizeof(foo); } //returns typically 8 or 4
If this seems confusing, it basically exists to maintain backwards compatibility with C.
And, of course,
sizeof name_of_struct
is a valid expression only when name_of_struct is an object (not just a type); writing
sizeof(struct name_of_struct)
will not compile unless name_of_struct is already defined (complete type) to be a struct (or class). But wait, there's more! If both exist then
sizeof(struct name_of_struct)
will get you the size of the type, not the object, whereas both
sizeof(name_of_struct)
and
(sizeof name_of_struct)
will get you the size of the object.
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