Unions and Enumerations

Back

Loading concept...

🏠 The Magic Toolbox: Unions & Enumerations in C

Imagine you have a special toolbox. But this isn’t just any toolboxβ€”it’s a shape-shifting one!


🎯 What You’ll Learn

  • Unions – One space, many faces
  • Structure vs Union – Why choose one over the other?
  • Enumerations – Giving names to numbers
  • typedef – Creating your own nicknames

πŸ“¦ Chapter 1: Unions β€” The Shape-Shifting Box

What is a Union?

Think of a union like a magic box that can hold different thingsβ€”but only ONE thing at a time.

Real-Life Example:

  • You have a lunchbox
  • It can hold a sandwich OR an apple OR a juice box
  • But NOT all three at once!
  • The box is always the same size
union LunchBox {
    char sandwich[20];
    int apple_count;
    float juice_ml;
};

How Unions Work

union LunchBox myLunch;

myLunch.apple_count = 3;
// Now the box holds apples!

myLunch.juice_ml = 250.5;
// Poof! Apples gone, now juice!

The Magic Rule: When you put something new in, the old thing disappears. The box only remembers the last thing you put in.

Why Use Unions?

Memory Saver! 🧠

union SmallBox {
    int number;     // 4 bytes
    char letter;    // 1 byte
    float decimal;  // 4 bytes
};
// Total size: 4 bytes (biggest member)

The union is only as big as its largest member. Smart, right?


βš”οΈ Chapter 2: Structure vs Union β€” The Big Showdown

The Key Difference

Think of it this way:

Feature Structure 🏠 Union πŸ“¦
Memory Separate rooms for each item One room shared by all
Access All members at once One member at a time
Size Sum of all members Size of largest member

Structure: A House with Many Rooms

struct House {
    int bedroom;     // 4 bytes
    char kitchen;    // 1 byte
    float bathroom;  // 4 bytes
};
// Total: 9+ bytes (each has own space)

Union: A Room That Transforms

union MagicRoom {
    int bedroom;     // 4 bytes
    char kitchen;    // 1 byte
    float bathroom;  // 4 bytes
};
// Total: 4 bytes (they share!)

Visual Comparison

Structure Memory:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ bedroom β”‚ kitchen β”‚bathroom β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  4 bytes   1 byte   4 bytes

Union Memory:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  bedroom/kitchen/bathroom   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         4 bytes total

When to Use What?

  • Structure: When you need ALL data together (like a person’s name AND age AND height)
  • Union: When you need ONLY ONE value at a time (like a value that’s either an integer OR a float)

🏷️ Chapter 3: Enumerations β€” Names for Numbers

The Problem

int day = 3;  // What day is this? πŸ€”

Is 3 Tuesday? Wednesday? We don’t know!

The Solution: enum

enum Weekday {
    SUNDAY,    // = 0
    MONDAY,    // = 1
    TUESDAY,   // = 2
    WEDNESDAY, // = 3
    THURSDAY,  // = 4
    FRIDAY,    // = 5
    SATURDAY   // = 6
};

Now we can write:

enum Weekday today = WEDNESDAY;
// Much clearer! πŸŽ‰

Custom Starting Values

enum Months {
    JAN = 1,   // Start from 1!
    FEB,       // = 2
    MAR,       // = 3
    APR        // = 4
};

Why Enums Are Awesome

  1. Readable Code πŸ“–

    // Confusing:
    if (status == 2) { }
    
    // Clear:
    if (status == SUCCESS) { }
    
  2. Prevents Mistakes πŸ›‘οΈ

    • You can’t accidentally use wrong numbers
  3. Easy to Change πŸ”§

    • Update enum, all code updates automatically

Practical Example

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
};

enum TrafficLight signal = RED;

if (signal == RED) {
    printf("Stop!");
} else if (signal == GREEN) {
    printf("Go!");
}

✨ Chapter 4: typedef β€” Creating Nicknames

What is typedef?

typedef lets you create shorter names for types. Like a nickname!

Real Life:

  • Your friend β€œChristopher” might be called β€œChris”
  • Same person, shorter name!

Basic typedef

typedef unsigned long int BigNumber;

// Now instead of:
unsigned long int population;

// You can write:
BigNumber population;

typedef with Structures

Without typedef:

struct Student {
    char name[50];
    int age;
};

struct Student alice;  // Must say "struct"

With typedef:

typedef struct {
    char name[50];
    int age;
} Student;

Student alice;  // Cleaner! No "struct"

typedef with Unions

typedef union {
    int whole;
    float decimal;
} Number;

Number value;
value.whole = 42;

typedef with Enums

typedef enum {
    SMALL,
    MEDIUM,
    LARGE
} Size;

Size shirtSize = MEDIUM;

Why Use typedef?

Benefit Example
Shorter code BigNum vs unsigned long int
Cleaner syntax Student s vs struct Student s
Easy changes Change once, updates everywhere
Readable Milliseconds tells you the unit

🎨 Putting It All Together

Here’s a real example combining everything:

// Create nickname for enum
typedef enum {
    CIRCLE,
    SQUARE,
    TRIANGLE
} ShapeType;

// Union to store different shape data
typedef union {
    float radius;        // for circle
    float side;          // for square
    float base, height;  // for triangle
} ShapeData;

// Structure combining type and data
typedef struct {
    ShapeType type;
    ShapeData data;
} Shape;

// Usage
Shape myShape;
myShape.type = CIRCLE;
myShape.data.radius = 5.0;

🧠 Quick Memory Tips

UNION = One room, many uses
        (saves space, one at a time)

STRUCT = Many rooms, one house
         (all data together)

ENUM = Names for numbers
       (readable, safe)

TYPEDEF = Nicknames for types
          (shorter, cleaner)

🎯 Key Takeaways

  1. Union shares memoryβ€”only use one member at a time
  2. Structure gives each member its own space
  3. Enum makes code readable with named constants
  4. typedef creates shorter, cleaner type names

You did it! πŸŽ‰ Now you know how to create your own custom types in C!


graph LR A["User-Defined Types"] --> B["Union"] A --> C["Enum"] A --> D["typedef"] B --> E["Shares Memory"] B --> F["One Value at Time"] C --> G["Named Constants"] C --> H["Starts at 0"] D --> I["Type Nicknames"] D --> J["Cleaner Code"]

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.