π 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
-
Readable Code π
// Confusing: if (status == 2) { } // Clear: if (status == SUCCESS) { } -
Prevents Mistakes π‘οΈ
- You canβt accidentally use wrong numbers
-
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
- Union shares memoryβonly use one member at a time
- Structure gives each member its own space
- Enum makes code readable with named constants
- 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"]
