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?
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.
The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With