Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 3 — Unions

Lesson 15 of 32 in the free C Language notes on Siksha Sarovar, written by Rohit Jangra.

Unions in C

A union is a user-defined data type similar to a structure, but all members share the same memory location. The size of a union is equal to the size of its largest member.

---

Defining and Using a Union

union Data {
    int i;
    float f;
    char c;
};

union Data d;
d.i = 65;
printf("int: %d\n", d.i);   /* 65 */

d.f = 3.14;
printf("float: %f\n", d.f); /* 3.14 */
/* d.i is now corrupted — only one member valid at a time */

---

Structure vs Union

FeatureStructureUnion
MemorySeparate memory for each memberShared memory for all members
SizeSum of all member sizes (+ padding)Size of largest member
AccessAll members accessible simultaneouslyOnly one member valid at a time
Use caseStore different data togetherSave memory when only one field needed

---

Size Example

struct S {
    int i;     /* 4 bytes */
    float f;   /* 4 bytes */
    char c;    /* 1 byte  */
};             /* sizeof = 12 (with padding) */

union U {
    int i;     /* 4 bytes */
    float f;   /* 4 bytes */
    char c;    /* 1 byte  */
};             /* sizeof = 4 (largest member) */

---

Practical Use: Variant Records

Unions are useful when a variable can hold different types at different times:

struct Shape {
    int type;   /* 0 = circle, 1 = rectangle */
    union {
        struct { float radius; } circle;
        struct { float width, height; } rect;
    } data;
};

---

Initialising a Union

Only the first member can be initialised in the declaration:

union Data d = {42};   /* initialises d.i = 42 */