Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

struct

sizeof

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?

like image 617
Ninad Page Avatar asked Oct 03 '10 10:10

Ninad Page


People also ask

Why sizeof empty struct is 1?

C++ The C++ standard does not permit objects (or classes) of size 0. This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1.

What is the size of empty class and why?

It is known that size of an empty class is not zero. Generally, it is 1 byte.

Can we define empty structure in C?

Empty struct in C is undefined behaviour (refer C17 spec, section 6.7. 2.1 ): If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.

What is the size of empty class in bytes?

Size of an empty class is not zero. It is 1 byte generally.


2 Answers

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 :)

like image 94
Prasoon Saurav Avatar answered Sep 22 '22 23:09

Prasoon Saurav


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

like image 29
vog Avatar answered Sep 21 '22 23:09

vog