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.
Practice
struct and a union in C++?Solution
Step 1: Understand memory allocation in struct
A struct allocates separate memory for each member, so all members can hold values simultaneously.Step 2: Understand memory allocation in union
A union shares the same memory space for all members, so only one member can hold a valid value at a time.Final Answer:
A struct stores all members separately; a union shares memory among members. -> Option AQuick Check:
Struct = separate memory, Union = shared memory [OK]
- Thinking union stores all members separately
- Confusing struct and union memory sharing
- Assuming both have same memory behavior
Data with an int and a float member?Solution
Step 1: Recall union syntax
The correct syntax uses the keywordunion, followed by the name, and braces enclosing members separated by semicolons.Step 2: Check each option
union Data { int i; float f; }; matches correct syntax. struct Data { int i; float f; }; usesstruct, not union. union Data ( int i; float f; ); uses parentheses instead of braces. union Data = { int i; float f; }; uses an assignment which is invalid.Final Answer:
union Data { int i; float f; }; -> Option CQuick Check:
Union syntax = keyword + braces + members [OK]
- Using struct keyword instead of union
- Using parentheses instead of braces
- Trying to assign values in definition
union Number {
int i;
float f;
};
int main() {
Number n;
n.i = 65;
std::cout << n.f << std::endl;
return 0;
}Solution
Step 1: Understand union memory sharing
Assigning 65 ton.istores the integer bits in the shared memory.Step 2: Interpret bits as float
Printingn.freads the same bits as a float, resulting in a floating-point number representing the bit pattern of 65, not the integer 65.Final Answer:
A floating-point number representing the bit pattern of 65 -> Option AQuick Check:
Union shares bits; reading different type shows bit pattern [OK]
- Expecting integer 65 to print as float 65.0
- Assuming union stores separate copies
- Thinking code causes compilation error
struct Data {
int x;
union {
int i;
float f;
} u;
};
int main() {
Data d;
d.x = 10;
d.u.i = 20;
d.u.f = 3.14;
std::cout << d.x << ", " << d.u.i << std::endl;
return 0;
}Solution
Step 1: Analyze union member assignments
Assigningd.u.i = 20;thend.u.f = 3.14;overwrites the same memory because union members share memory.Step 2: Understand reading union members
Readingd.u.iafter assigningd.u.fgives an undefined or unexpected value because only the last assigned member is valid.Final Answer:
Accessing union member after assigning another member leads to undefined value. -> Option BQuick Check:
Union stores one value; reading old member is invalid [OK]
- Thinking struct cannot have union member
- Ignoring union memory sharing rules
- Expecting both union members to hold values simultaneously
Solution
Step 1: Understand memory needs
Since only one value (int or float) is needed at a time, memory can be saved by sharing storage.Step 2: Choose union for shared memory
A union allows storing either int or float in the same memory space, saving memory compared to a struct which stores both separately.Step 3: Evaluate other options
Using two separate variables wastes memory. A class with private members behaves like struct in memory. Struct stores both values simultaneously, using more memory.Final Answer:
Use a union with int and float members. -> Option DQuick Check:
Union saves memory when only one value needed [OK]
- Choosing struct and wasting memory
- Using separate variables unnecessarily
- Confusing class with memory optimization
Ready to prove it?
Pass the test and this pattern moves unknown
