Home > Article > Backend Development > Why Does an Empty Class in C Have a Size of 1?
Understanding the Size of Empty Classes in C
In C , the size of an empty class is not zero. This might seem counterintuitive at first, but there's a crucial reason behind it.
Why the Size is Not Zero
The C standard prohibits objects and their classes from having a size of 0. This restriction prevents two distinct objects from sharing the same memory address. Even an empty class must have a size of at least 1 to ensure unique object addresses.
In the example provided:
<code class="cpp">#include <iostream> class Test { }; int main() { std::cout << sizeof(Test); return 0; }</code>
The output is 1 because the Test class, despite being empty, has a size of 1 to comply with the standard. Every class in C , regardless of its content, must have a non-zero size to avoid potential memory address conflicts.
The above is the detailed content of Why Does an Empty Class in C Have a Size of 1?. For more information, please follow other related articles on the PHP Chinese website!