Difference between Structure and Union in C

// Quick Answer
  • A structure stores multiple values in separate memory locations.
  • A union shares the same memory location for all members.
  • Structures use more memory; unions use memory efficiently.

What is a structure?

A structure in C is a user-defined data type that allows storing different types of variables under one name, each with its own memory space.

struct Student {
  int id;
  float marks;
};

Each member (id, marks) has separate memory.

What is a union?

A union is similar to a structure, but all members share the same memory location.

union Data {
  int id;
  float marks;
};

Only one value can be stored at a time.

Key differences

Feature        | Structure             | Union
--------------------------------------------------------
Memory         | Separate for each     | Shared memory
Size           | Sum of all members    | Size of largest member
Usage          | Store multiple values | Store one value at a time
Modification   | Independent           | Overwrites previous value

Memory concept

  • Structure → each variable gets its own memory block
  • Union → all variables use the same memory block

Example: Structure

struct Student s;
s.id = 1;
s.marks = 95.5;

Example: Union

union Data d;
d.id = 1;
d.marks = 95.5;  // overwrites id

When to use structure

  • When you need to store multiple values together
  • When data should remain independent

When to use union

  • When memory efficiency is important
  • When only one value is needed at a time
📌 Real-world fact

Unions are often used in low-level programming like embedded systems where memory is very limited.

Summary

Structures store multiple values with separate memory, while unions share memory among all members. This makes structures flexible and unions memory-efficient.