A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The 'struct' keyword is used to create a structure.
- C++ does not allow objects of size 0, because different objects must have distinct memory addresses.
- Therefore, even an empty class or structure in C++ occupies at least 1 byte of memory.
- This rule ensures that every object can be uniquely identified in memory.
- In C, empty structures are not standard, though some compilers (like GCC) allow them as an extension, with undefined behavior.
Note: C99 says-Â If the struct-declaration-list contains no named members, the behavior is undefined.Â
C program with an empty structure:
#include <stdio.h>
int main()
{
// Empty Structure
struct empty {
};
struct empty empty_struct;
// Printing the Size of Struct
printf("Size of Empty Struct in C programming = %ld", sizeof(empty_struct));
}
Output
Size of Empty Struct in C programming = 0
C++ program with an empty structure:
#include <iostream>
using namespace std;
int main()
{
// Empty Struct
struct empty {
};
// Initializing the Variable
// of Struct type
struct empty empty_struct;
// Printing the Size of Struct
cout << "Size of Empty Struct in C++ Programming = " << sizeof(empty_struct);
}
Output
Size of Empty Struct in C++ Programming = 1