TalentJR

Lesson 10

Unions & Enums

Model data compactly and clearly

1What Are Unions?✨

Unions in C allow you to store different data types in the same memory location. This helps save space when you know that only one of the data types will be used at a time.

2Here’s how you declare a union:🎯

💻 code
```c
union Data {
    int intValue;
    float floatValue;
    char charValue;
};
```

3Why Use Unions?💡

  • ✓ Save memory by using the same space for different types
  • ✓ Efficient when managing multiple data types
  • ✓ Useful in situations like embedded systems

4Using Unions🚀

To use a union, you can define a variable of the union type and then access its members. Only one member can hold a value at a time.

5Example:🔍

💻 code
```c
union Data data;
data.intValue = 10;
printf("%d\n", data.intValue);
data.floatValue = 220.5;
printf("%f\n", data.floatValue);
```

6What Are Enums?⭐

Enums, short for enumerations, are a way to define a variable that can hold a set of predefined constants. This makes your code more readable and manageable.

7Declaring an Enum:🧩

  • ```c
  • enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • ```

8Benefits of Enums🎈

  • ✓ Improves code clarity by using meaningful names
  • ✓ Reduces errors by restricting values
  • ✓ Makes debugging easier

9Using Enums in Code✨

You can use enums in switch statements or as variables to enhance code flow.

10Example:🎯

💻 code
```c
enum Day today = Wednesday;
switch(today) {
    case Sunday: printf("It's Sunday!\n"); break;
    case Wednesday: printf("It's Wednesday!\n"); break;
    }
```

11What You'll Build This Grade💡

  • ✓ Compact data structures for efficient programs
  • ✓ Enhanced readability with enums
  • ✓ Applications that manage various types of data with ease
  • ✓ Improved debugging and maintenance of your code

🎯 Practice Challenges

Master Unions & Enums by completing all 3 difficulty levels

🟢 EASY

Unions & Enums - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

Unions & Enums - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

Unions & Enums - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master Unions & Enums? 🚀

Complete the challenges, take the quiz and keep your learning streak going!