In C programming language, structure and union are both composite data types that allow you to group related data elements of different data types together. However, there are some key differences between the two:
Memory allocation:
A structure allocates separate memory for each member variable declared inside the structure.
A union allocates memory that is shared by all its member variables, and only enough memory to hold the largest member.
Size:
The size of a structure is the sum of the sizes of all its members.
The size of a union is the size of its largest member.
Accessing members:
Members of a structure are accessed using dot (.) notation.
Members of a union are accessed using the same syntax as structure members, but only one member can be accessed at a time.
Initialization:
You can initialize individual members of a structure.
You can initialize only the first member of a union.
Here's an example that demonstrates the difference between a structure and a union
#include <stdio.h>
struct student {
int roll_no;
char name[20];
float marks;
};
union data {
int i;
float f;
char c;
};
int main() {
// Declare and initialize a structure variable
struct student s = { 1, "John", 85.5 };
printf("Size of structure: %ld\n", sizeof(s)); // Output: 28
// Declare and initialize a union variable
union data d = { 'A' };
printf("Size of union: %ld\n", sizeof(d)); // Output: 4
return 0;
}
In the example above, the student structure contains three members of different data types, so its size is the sum of the sizes of those members, which is 28 bytes on a typical 64-bit system. On the other hand, the data union contains three members of different data types that share the same memory, and its size is only 4 bytes, because char is the smallest member.
In summary, structures and unions are both powerful tools for organizing data in C programming language, and their different features make them useful in different situations.