Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can sizeof return 0 (zero)

Tags:

c++

c

sizeof

Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?

like image 471
TheJuice Avatar asked Apr 13 '10 18:04

TheJuice


People also ask

What does sizeof return?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What does sizeof array return?

The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.

Does sizeof return number of bytes?

The sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory. For struct types, that value includes any padding, as the preceding example demonstrates.

Does sizeof return an int?

sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.


1 Answers

In C++ an empty class or struct has a sizeof at least 1 by definition. From the C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size."

In C an empty struct is not permitted, except by extension (or a flaw in the compiler).

This is a consequence of the grammar (which requires that there be something inside the braces) along with this sentence from 6.7.2.1/7 "Structure and union specifiers": "If the struct-declaration-list contains no named members, the behavior is undefined".

If a zero-sized structure is permitted, then it's a language extension (or a flaw in the compiler). For example, in GCC the extension is documented in "Structures with No Members", which says:

GCC permits a C structure to have no members:

 struct empty {  }; 

The structure will have size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type char.

like image 161
Michael Burr Avatar answered Sep 18 '22 12:09

Michael Burr