Structures and unions help group different data types together. They let you keep related information in one place.
Structure vs union comparison in C++
struct StructName {
type1 member1;
type2 member2;
// more members
};
union UnionName {
type1 member1;
type2 member2;
// more members
};A structure stores all members separately, each with its own space.
A union stores all members in the same memory space, so only one member can hold a value at a time.
struct Person {
char name[20];
int age;
};union Data {
int i;
float f;
char str[20];
};This program shows how a structure keeps all data separately, while a union shares memory for all members. Changing one union member affects others.
#include <iostream>
#include <cstring>
struct Person {
char name[20];
int age;
};
union Data {
int i;
float f;
char str[20];
};
int main() {
Person p1;
strcpy(p1.name, "Alice");
p1.age = 30;
std::cout << "Structure Person:\n";
std::cout << "Name: " << p1.name << "\n";
std::cout << "Age: " << p1.age << "\n\n";
Data d;
d.i = 10;
std::cout << "Union Data after setting int: " << d.i << "\n";
d.f = 220.5f;
std::cout << "Union Data after setting float: " << d.f << "\n";
strcpy(d.str, "Hello");
std::cout << "Union Data after setting string: " << d.str << "\n";
std::cout << "Union Data int now: " << d.i << " (may be garbage)\n";
return 0;
}Structures use more memory because each member has its own space.
Unions save memory but only one member can be used at a time.
Accessing a union member different from the last one set can cause unexpected values.
Structures store all members separately and keep all values.
Unions share memory among members and only one value is valid at a time.
Use structures for grouping related data, and unions to save memory when only one value is needed at a time.