What is the difference between structure and union in C?
| Structure | Union |
|---|---|
| Each member has separate memory | All members share the same memory |
| Size is the sum of members (plus padding) | Size is the size of the biggest member |
| All members hold values together | Only one member holds a valid value |
#include <stdio.h>
struct S { int i; double d; };
union U { int i; double d; };
int main(void) {
printf("%zu %zu\n", sizeof(struct S), sizeof(union U));
return 0;
}
Output:
Output of the above program is
16 8
See Structures and Union.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |