sizeof empty structure is 0 in C and 1 in C++ why? [duplicate]
Asked Answered
N

3

42

Possible Duplicates:
Empty class in C++
What is the size of an empty struct in C?

I read somewhere that size of an empty struct in C++ is 1. So I thought of verifying it. Unfortunately I saved it as a C file and used <stdio.h> header and I was surprised to see the output. It was 0.

That means

struct Empty {

};

int main(void)
{
  printf("%d",(int)sizeof(Empty));
}

was printing 0 when compiled as a C file and 1 when compiled as a C++ file. I want to know the reason. I read that sizeof empty struct in C++ is not zero because if the size were 0 then two objects of the class would have the same address which is not possible. Where am I wrong?

Nephrectomy answered 3/10, 2010 at 10:10 Comment(9)
-1 No, you didn't compile that as C.Clemenceau
@Ninad : Did you try this?Dobsonfly
When you're asking questions at this level of language please include the compiler name and version.Estaminet
This is a super-duplicate. For C, duplicate of this (answer: it's ill-formed). In C++, this (answer: it must have a size greater than zero so space can be allocated for it).Fpc
@GMan : Oh damn! I thought it was really a good question, dupe though :) Thanks for the links.Dobsonfly
-1 by me too. the sizeof cannot compileCushman
Why don't post an answer explaining it instead of downvoting?Buttonhook
@Buttonhook i like to post answers to actual questions.Cushman
@chakrit: duplicate questions do not warrant any answer, they just need be redirected to their doppleganger.Commercialism
D
22

You cannot have an empty structure in C. It is a syntactic constraint violation. However gcc permits an empty structure in C as an extension. Furthermore the behaviour is undefined if the structure does not have any named member because

C99 says :

If the struct-declaration-list contains no named members, the behavior is undefined.

So

struct Empty {}; //constraint violation

struct Empty {int :0 ;}; //no named member, the behaviour is undefined.

And yes size of an empty struct is C++ cannot be zero :)

Dobsonfly answered 3/10, 2010 at 10:12 Comment(0)
O
7

There are several good reasons. Among others, this is to ensure that pointer arithmetics over pointers to that structure don't lead to an infinite loop. More information:

http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

Optimist answered 3/10, 2010 at 10:15 Comment(0)
V
6

Here is a wonderful article describing why this occurs, and more pertinently, a (safe) way around it :)

http://www.cantrip.org/emptyopt.html

Valentinevalentino answered 3/10, 2010 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.