🏗️ C++ struct
vs union
– What’s the Difference?
Both struct
and union
are used to group variables, but they treat memory very differently. Let’s break it down! 🧠
🧬 Key Differences
- struct: Each member has its own memory.
- union: All members share the same memory.
- struct: Can use all members at the same time.
- union: Only one member holds a value at a time.
- struct: Takes more memory.
- union: Saves memory – useful in embedded systems or when space matters!
🔧 Example: struct
#include <iostream> using namespace std; struct Person { int age; float height; }; int main() { Person p; p.age = 25; p.height = 5.9; cout << "Age: " << p.age << endl; cout << "Height: " << p.height << endl; return 0; }
🔧 Example: union
#include <iostream> using namespace std; union Data { int i; float f; }; int main() { Data d; d.i = 10; cout << "Int: " << d.i << endl; d.f = 3.14; cout << "Float: " << d.f << endl; // Note: d.i is now overwritten! return 0; }
🧠 Memory Trick
- struct = multi-room apartment 🏢
- union = single-room tent 🏕️
✅ When to Use?
- Use struct: When you need to store and access multiple values at once.
- Use union: When only one value is needed at a time to save memory.