20

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.

0

3 Answers 3

29

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.

Sign up to request clarification or add additional context in comments.

2 Comments

One additional minor note, the struct and class keywords are interchangeable in this context. sizeof(struct foo) and sizeof(class foo) would both work. You don't see the latter very often though, since this mainly comes up in the context of interoperating with C code.
Furthermore struct name_of_struct i.e. an elaborated type specifier also declares name_of_struct. This doesn't make a difference in this particular case, since in order to use sizeof, name_of_struct must be defined, and therefore declared prior. But in another case, it can make a difference.
1

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.

Comments

0

As far as I know: the difference is c style struct notation versus C++ notation.

2 Comments

No, they are both C++. sizeof(name_of_struct) is only C++ i.e. not C, unless name_of_struct is also a typedef.
I agree wholeheartedly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.