Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sizeof(struct name_of_struct) vs sizeof(name_of_struct)?

Tags:

c++

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.

like image 342
Kunseok Avatar asked Jun 13 '19 19:06

Kunseok


People also ask

Is sizeof for a struct equal to the sum of sizeof of each member?

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.


2 Answers

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.

like image 104
PSkocik Avatar answered Oct 17 '22 14:10

PSkocik


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.

like image 1
John Lakos Avatar answered Oct 17 '22 16:10

John Lakos