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.