๐ Definition Recap
Concept | Description |
|---|---|
๐งฑ Structure ( | A collection of variables (members) of different types, stored in separate memory locations, but grouped under a single name. |
๐งฌ Union ( | Similar to a structure, but all members share the same memory location, and only one member can hold a value at a time. |
๐ง Memory Allocation โ The Core Difference
๐ In a struct:
Each member has its own memory location.
struct Sample {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};Total size = sum of all members + padding (usually around 12 bytes)
๐ In a union:
All members share the same memory location โ the size of the largest member decides the total size.
union Sample {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};Total size = 4 bytes (largest of the three)
๐ Comparison Table
๐ข Feature | ๐งฑ Structure | ๐งฌ Union |
|---|---|---|
๐ง Memory | Sum of all members' sizes (+ padding) | Size of the largest member |
๐ง Storage | Each member has a separate location | All members share the same memory |
๐ Active members | All can store and hold values simultaneously | Only one member holds value at a time |
๐ Value Retention | Value of all members is retained | Assigning a value to one member will overwrite others |
๐ฅ Initialization | All members can be initialized | Only the first member can be initialized at declaration |
๐งพ Use Cases | Complex data records (e.g., Employee) | Space-saving when only one field is needed at a time |
๐งฐ Efficiency | Less memory efficient | More memory efficient |
๐งช Syntax |
|
|
<div class="infographic-csvurun">
<style>
.infographic-csvurun {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--code-bg: #1e1e2e;
--code-text: #d4d4e0;
--syn-keyword: #c586c0;
--syn-func: #dcdcaa;
--syn-string: #ce9178;
--syn-comment: #6a9955;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--warn: #b45309;
--warn-soft: #fdf0dc;
}
.infographic-csvurun[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--code-bg: #0d0d14;
--code-text: #d4d4e0;
--ok: #5cd6a0;
--ok-soft: #16342a;
--warn: #e0a458;
--warn-soft: #3a2c14;
}
.infographic-csvurun {
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
background: var(--paper);
color: var(--ink);
font-family: 'Inter', -apple-system, sans-serif;
padding: 0 clamp(1rem, 4vw, 2.25rem) 1.25rem;
}
.infographic-csvurun *, .infographic-csvurun *::before, .infographic-csvurun *::after {
box-sizing: border-box;
}
.infographic-csvurun h1 {
font-family: 'Fraunces', Georgia, serif;
font-weight: 600;
font-size: clamp(1.3rem, 3.5vw, 1.7rem);
margin: 1.25rem 0 0.2rem;
text-align: center;
}
.infographic-csvurun .subhead { color: var(--ink-soft); font-size: 0.85rem; margin-bottom: 1.1rem; text-align: center; }
.infographic-csvurun .chip-row { display: flex; justify-content: center; gap: 0.45rem; margin-bottom: 1rem; }
.infographic-csvurun .chip {
all: unset;
cursor: pointer;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.78rem;
font-weight: 600;
padding: 0.42rem 0.9rem;
border-radius: 20px;
border: 1px solid var(--line);
color: var(--ink-soft);
transition: background 0.2s, color 0.2s, border-color 0.2s;
}
.infographic-csvurun .chip:hover { border-color: var(--accent); }
.infographic-csvurun .chip.is-active { background: var(--accent); border-color: var(--accent); color: #fff; }
.infographic-csvurun .tab-panel { display: none; }
.infographic-csvurun .tab-panel.is-active { display: block; }
.infographic-csvurun .code-panel {
background: var(--code-bg);
color: var(--code-text);
border-radius: 8px;
padding: 0.65rem 0.9rem;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.76rem;
line-height: 1.55;
margin-bottom: 0.9rem;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.infographic-csvurun .code-panel .code-line { display: block; white-space: pre; }
.infographic-csvurun .code-panel .code-line.is-highlight {
background: rgba(91, 141, 239, 0.22);
box-shadow: inset 3px 0 0 var(--accent);
}
.infographic-csvurun .syn-keyword { color: var(--syn-keyword); }
.infographic-csvurun .syn-func { color: var(--syn-func); }
.infographic-csvurun .syn-string { color: var(--syn-string); }
.infographic-csvurun .syn-comment { color: var(--syn-comment); }
.infographic-csvurun .run-btn {
all: unset; cursor: pointer;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.8rem; font-weight: 600;
padding: 0.45rem 1rem;
border-radius: 999px;
background: var(--accent);
color: #fff;
margin-bottom: 1rem;
display: inline-block;
}
.infographic-csvurun .run-btn:hover { opacity: 0.88; }
.infographic-csvurun .run-btn:disabled { opacity: 0.5; cursor: default; }
.infographic-csvurun .mem-row { display: flex; justify-content: center; gap: 0.6rem; margin-bottom: 1rem; }
.infographic-csvurun .mem-cell { text-align: center; }
.infographic-csvurun .mem-name { font-family: 'IBM Plex Mono', monospace; font-size: 0.72rem; color: var(--ink-soft); margin-bottom: 0.3rem; }
.infographic-csvurun .mem-box {
height: 2.8rem;
width: 6.5rem;
border: 2px solid var(--line);
background: var(--paper-alt);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.85rem;
font-weight: 700;
color: var(--ink-soft);
transition: border-color 0.3s, background 0.3s, color 0.3s;
}
.infographic-csvurun .mem-box.is-set { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.infographic-csvurun .mem-box.is-corrupt { border-color: var(--warn); background: var(--warn-soft); color: var(--warn); }
.infographic-csvurun .console {
background: var(--code-bg);
color: var(--code-text);
border-radius: 8px;
padding: 0.7rem 0.9rem;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.8rem;
line-height: 1.6;
white-space: pre;
min-height: 3.2rem;
}
.infographic-csvurun .console .ok-tag { color: var(--ok); }
.infographic-csvurun .console .warn-tag { color: var(--warn); }
.infographic-csvurun .takeaway {
font-size: 0.82rem; color: var(--ink-soft);
margin-top: 1.3rem; border-top: 1px solid var(--line); padding-top: 0.9rem;
}
.infographic-csvurun .takeaway strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-csvurun * { transition: none !important; }
}
</style>
<h1>๐งช Code Comparison</h1>
<p class="subhead">Same sequence โ assign x, then y, then print both.</p>
<div class="chip-row" id="cmp-tabs">
<button class="chip is-active" data-tab="struct">๐งฑ Structure</button>
<button class="chip" data-tab="union">๐งฌ Union</button>
</div>
<!-- Structure example -->
<div class="tab-panel is-active" data-tab="struct">
<div class="code-panel" id="st-code">
<span class="code-line"><span class="syn-keyword">struct</span> Test { <span class="syn-keyword">int</span> x; <span class="syn-keyword">float</span> y; };</span>
<span class="code-line"> </span>
<span class="code-line"><span class="syn-keyword">struct</span> Test s;</span>
<span class="code-line" data-line="x">s.x = 10;</span>
<span class="code-line" data-line="y">s.y = 20.5;</span>
<span class="code-line"> </span>
<span class="code-line" data-line="p1"><span class="syn-func">printf</span>(<span class="syn-string">"x = %d\n"</span>, s.x);</span>
<span class="code-line" data-line="p2"><span class="syn-func">printf</span>(<span class="syn-string">"y = %.2f\n"</span>, s.y);</span>
</div>
<button class="run-btn" id="st-run">โถ Run</button>
<div class="mem-row">
<div class="mem-cell"><div class="mem-name">s.x</div><div class="mem-box" id="st-box-x">โ</div></div>
<div class="mem-cell"><div class="mem-name">s.y</div><div class="mem-box" id="st-box-y">โ</div></div>
</div>
<div class="console" id="st-console"></div>
</div>
<!-- Union example -->
<div class="tab-panel" data-tab="union">
<div class="code-panel" id="un-code">
<span class="code-line"><span class="syn-keyword">union</span> Test { <span class="syn-keyword">int</span> x; <span class="syn-keyword">float</span> y; };</span>
<span class="code-line"> </span>
<span class="code-line"><span class="syn-keyword">union</span> Test u;</span>
<span class="code-line" data-line="x">u.x = 10;</span>
<span class="code-line" data-line="y">u.y = 20.5;</span>
<span class="code-line"> </span>
<span class="code-line" data-line="p1"><span class="syn-func">printf</span>(<span class="syn-string">"x = %d\n"</span>, u.x);</span>
<span class="code-line" data-line="p2"><span class="syn-func">printf</span>(<span class="syn-string">"y = %.2f\n"</span>, u.y);</span>
</div>
<button class="run-btn" id="un-run">โถ Run</button>
<div class="mem-row">
<div class="mem-cell"><div class="mem-name">shared bytes as x</div><div class="mem-box" id="un-box-x">โ</div></div>
<div class="mem-cell"><div class="mem-name">shared bytes as y</div><div class="mem-box" id="un-box-y">โ</div></div>
</div>
<div class="console" id="un-console"></div>
</div>
<p class="takeaway" id="cmp-takeaway"></p>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-csvurun')
|| document.querySelector('.infographic-csvurun');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
function $(sel) { return wrapper.querySelector(sel); }
// ---- tabs ----
const tabs = wrapper.querySelectorAll('#cmp-tabs .chip');
const panels = wrapper.querySelectorAll('.tab-panel');
const takeaway = $('#cmp-takeaway');
const TAKEAWAY = {
struct: '<strong style="color:var(--ok);">๐ข Both values are safe</strong> โ x and y each have their own 4 bytes, so setting y never touches x.',
union: '<strong style="color:var(--warn);">๐ด x is corrupted</strong> โ x and y share the same 4 bytes, so writing y overwrote whatever x used to hold.'
};
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('is-active'));
tab.classList.add('is-active');
panels.forEach(p => p.classList.toggle('is-active', p.dataset.tab === tab.dataset.tab));
takeaway.innerHTML = TAKEAWAY[tab.dataset.tab];
});
});
takeaway.innerHTML = TAKEAWAY.struct;
function highlight(codeEl, id) {
codeEl.querySelectorAll('.code-line[data-line]').forEach(l => l.classList.toggle('is-highlight', l.dataset.line === id));
}
// ---- Structure example ----
const stCode = $('#st-code');
const stBoxX = $('#st-box-x'), stBoxY = $('#st-box-y');
const stConsole = $('#st-console');
$('#st-run').addEventListener('click', () => {
const btn = $('#st-run');
btn.disabled = true;
stBoxX.textContent = 'โ'; stBoxX.className = 'mem-box';
stBoxY.textContent = 'โ'; stBoxY.className = 'mem-box';
stConsole.textContent = '';
highlight(stCode, null);
const steps = [
() => { highlight(stCode, 'x'); stBoxX.textContent = '10'; stBoxX.className = 'mem-box is-set'; },
() => { highlight(stCode, 'y'); stBoxY.textContent = '20.5'; stBoxY.className = 'mem-box is-set'; },
() => { highlight(stCode, 'p1'); stConsole.innerHTML = 'x = 10 <span class="ok-tag">\u2705</span>'; },
() => { highlight(stCode, 'p2'); stConsole.innerHTML += '\ny = 20.50 <span class="ok-tag">\u2705</span>'; },
() => { highlight(stCode, null); btn.disabled = false; }
];
let i = 0;
(function next() { if (i >= steps.length) return; steps[i](); i++; setTimeout(next, 450); })();
});
// ---- Union example ----
const unCode = $('#un-code');
const unBoxX = $('#un-box-x'), unBoxY = $('#un-box-y');
const unConsole = $('#un-console');
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
function floatStr(v) {
if (Number.isNaN(v)) return 'NaN';
if (!Number.isFinite(v)) return v > 0 ? 'Infinity' : '-Infinity';
return String(Math.round(v * 100) / 100);
}
$('#un-run').addEventListener('click', () => {
const btn = $('#un-run');
btn.disabled = true;
unBoxX.textContent = 'โ'; unBoxX.className = 'mem-box';
unBoxY.textContent = 'โ'; unBoxY.className = 'mem-box';
unConsole.textContent = '';
highlight(unCode, null);
let corruptedX = 0;
const steps = [
() => {
highlight(unCode, 'x');
view.setInt32(0, 10, true);
unBoxX.textContent = '10'; unBoxX.className = 'mem-box is-set';
unBoxY.textContent = floatStr(view.getFloat32(0, true)); unBoxY.className = 'mem-box is-set';
},
() => {
highlight(unCode, 'y');
view.setFloat32(0, 20.5, true);
unBoxY.textContent = '20.5'; unBoxY.className = 'mem-box is-set';
corruptedX = view.getInt32(0, true);
unBoxX.textContent = corruptedX; unBoxX.className = 'mem-box is-corrupt';
},
() => { highlight(unCode, 'p1'); unConsole.innerHTML = 'x = ' + corruptedX + ' <span class="warn-tag">\u26a0\ufe0f overwritten</span>'; },
() => { highlight(unCode, 'p2'); unConsole.innerHTML += '\ny = 20.50 <span class="ok-tag">\u2705</span>'; },
() => { highlight(unCode, null); btn.disabled = false; }
];
let i = 0;
(function next() { if (i >= steps.length) return; steps[i](); i++; setTimeout(next, 450); })();
});
})();
</script>๐ฏ When to Use What?
Situation | Use |
|---|---|
You need to store multiple pieces of information together | โ Use Structure |
You need to store only one of many types to save space | โ Use Union |
๐ฆ Real-Life Analogy
Concept | Analogy |
|---|---|
Structure | A lunchbox with compartments: rice, curry, salad โ all stored separately but together |
Union | A single glass where you can pour either water or juice, but not both at the same time |