We all know that sizeof an empty class or an object of empty class will be 1 byte.
I came across something where sizeof
a class and its object is coming as 0. The program is syntactically correct as there were no compilation or run time errors. Is this undefined behavior? The use case I'm trying to execute makes any sense and looks like a valid one? Is it a big blunder to not to give exact subscript or size for an array in the class? The code snippet is as below:
#include<iostream>
using namespace std;
class A
{
char a[];
};
int main()
{
A b;
cout<<sizeof(A)<<endl;
cout<<sizeof(b)<<endl;
return 0;
}
output:
0
0
The sizeof
an empty class is one byte (non zero basically) and the reason for that is said like "To make sure that different objects have different addresses".
What happens in this case then when sizeof
class is coming a zero?
Note: Observed the same behavior for int a[]
as well.
sizeof never returns 0 in C and in C++. Every time you see sizeof evaluating to 0 it is a bug/glitch/extension of a specific compiler that has nothing to do with the language. reference or it didn't happen.
The size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses.
sizeof always returns size as the number of bytes. But according to wikipedia: In the programming languages C and C++, the unary operator sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type.
The size of object of a class depends on the no. of bytes occupied by the data members of the class. }; The object of class student will occupy space of 8 bytes.
It's called "flexible array member" and it's a feature of C99 (I think). It's not valid C++ - you don't have warnings/errors, probably because the compiler supports it as an extension.
Compiling with -Wall -Wextra -pedantic -std=c++NN
(98, 03, 11, 14, ..) should generate warning (the last two flags will disable any compiler extensions).
You can see some information in this related question: Is using flexible array members in C bad practice?
For example, here's what GCC says about this:
In ISO C99, you would use a flexible array member, which is slightly different in syntax and semantics:
...
Flexible array members have incomplete type, and so the sizeof operator may not be applied. As a quirk of the original implementation of zero-length arrays, sizeof evaluates to zero.
(source: https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html).
This explains the 0
size of char a[]
and not the 0 for the class, but as I already mentioned - it's a C feature and not a valid C++.
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