Home  >  Article  >  Backend Development  >  Why Does an Empty Class in C Have a Size of 1?

Why Does an Empty Class in C Have a Size of 1?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 21:25:29821browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn