100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Unions in C

Learn C unions: syntax, how members share the same memory, sizeof(union) rules, and the type-punning pitfall of reading a member you did not last write.

Pointers, Structures & UnionsIntermediate12 min readJul 7, 2026
Analogies

1. Introduction

A union in C is a user-defined data type, declared similarly to a structure, whose members all share the same memory location instead of each having their own separate space. This means a union can hold only one of its members' values at any given time, making unions extremely memory-efficient when you need to represent a value that could be one of several different types but never more than one simultaneously — for example, a variant/tagged data type, low-level hardware register interpretation, or a value that is sometimes an int and sometimes a float depending on context.

🏏

Cricket analogy: A union is like a single all-purpose kit bag slot that holds either the bat or the pads at any one time, never both simultaneously, useful when a player's role, batter or keeper, is decided only at the moment of selection.

2. Syntax

A union is defined using the union keyword with syntax nearly identical to a structure: union UnionName { dataType member1; dataType member2; ... }; Variables are declared as union UnionName varName;, and members are accessed with the dot operator (.) for a direct union variable and the arrow operator (->) through a pointer to a union, exactly as with structures. The key semantic difference from a structure is memory layout: all members of a union start at the same base address and overlap each other.

🏏

Cricket analogy: Declaring a union like the team's kit locker is nearly identical syntax to declaring the equipment list structure, but unlike separate labeled shelves for bat and pads, the union's shelf is a single overlapping space where storing the bat and storing the pads both occupy the exact same spot.

3. Explanation

Because all members of a union occupy the same memory location, sizeof(union) is equal to the size of its largest member (plus any padding needed so the union's total size is a multiple of its required alignment), not the sum of all members' sizes as with a structure. Writing to one member and then reading a different member reinterprets the same underlying bytes according to the second member's type — this technique is called type punning. In strict standard C, reading a union member other than the one most recently written is technically undefined behavior, although GNU C (via GCC/Clang extensions) explicitly permits it and it is a widely used, well-understood idiom for low-level bit manipulation, such as inspecting the individual bytes of a float or checking a system's endianness. Portable, standard-conforming C code that needs guaranteed type punning should instead use memcpy() to reinterpret bytes, since that approach is well-defined in all conforming implementations. Unions are commonly paired with an explicit 'tag' field in an enclosing structure (a discriminated/tagged union pattern) so the program can track which member was last written and is therefore safe to read.

🏏

Cricket analogy: A union's size equaling its largest member is like the kit bag being sized for the bulkiest item, the bat, not the sum of bat plus pads plus gloves; storing the bat then reading it as pads is type punning, risky unless you use a well-defined method like memcpy to check the bag's actual contents, and pairing it with a tag telling you which item was last packed.

Only one member of a union is 'valid' at any given time — the one that was most recently written. Writing through one member and then reading through a different member (type punning) reinterprets the same raw bytes as a different type, which is undefined behavior under strict ISO C, even though many compilers (like GCC and Clang) explicitly document support for it as an extension and it is common in real-world systems code. If you need guaranteed portable behavior, use memcpy() to copy the bytes into the target type instead of relying on union type punning, or pair the union with a separate tag/enum field that records which member is currently valid so your own code (not the compiler) enforces correct usage.

Tip: A very common, safe use of unions is building a 'tagged union' — pair a union with an enum field in a wrapping struct, e.g. struct Value { enum { INT_T, FLOAT_T } tag; union { int i; float f; } data; };. Checking the tag before accessing data.i or data.f ensures you always read the member that was actually written.

4. Example

c
#include <stdio.h>

union Data {
    int i;
    float f;
    char bytes[4];
};

int main(void) {
    union Data d;

    d.i = 65;
    printf("After setting d.i = 65:   d.i = %d\n", d.i);

    d.f = 3.14f;              /* overwrites the same memory that held d.i */
    printf("After setting d.f = 3.14: d.f = %.2f\n", d.f);
    printf("d.i now reads garbage relative to int: %d (reinterpreted bytes)\n", d.i);

    printf("sizeof(union Data) = %zu bytes (size of largest member, float/int)\n",
           sizeof(union Data));

    /* Tagged union pattern: track which member is valid explicitly */
    struct Tagged {
        enum { INT_T, FLOAT_T } tag;
        union { int i; float f; } value;
    } t;
    t.tag = FLOAT_T;
    t.value.f = 9.5f;
    if (t.tag == FLOAT_T) {
        printf("Tagged union safely read as float: %.2f\n", t.value.f);
    }

    return 0;
}

5. Output

text
After setting d.i = 65:   d.i = 65
After setting d.f = 3.14: d.f = 3.14
d.i now reads garbage relative to int: 1078523331 (reinterpreted bytes)
sizeof(union Data) = 4 bytes (size of largest member, float/int)
Tagged union safely read as float: 9.50

/* Note: the exact integer value printed for d.i after writing d.f is
   platform/compiler dependent, since it is the raw bit pattern of the
   float reinterpreted as an int. */

6. Key Takeaways

  • All members of a union share the same memory address, so writing one member overwrites the others.
  • sizeof(union) equals the size of its largest member, unlike a struct where sizes add up (plus padding).
  • Only the most recently written member is guaranteed valid to read; reading a different member is type punning.
  • Type punning via unions is undefined behavior in strict ISO C but a documented extension in GCC/Clang and widely used in practice.
  • The tagged-union pattern (union + enum tag) is the safe, portable way to track which member currently holds valid data.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#UnionsInC#Unions#Syntax#Explanation#Example#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse