Skip to main content
C Programming Basics
CHAPTER 16 Beginner

Unions and Enumerations

Updated: May 17, 2026
5 min read

# CHAPTER 16

Unions and Enumerations

1. Introduction

While struct is the most common way to group data, C offers two other specialized tools: Unions for aggressive memory saving, and Enumerations (enum) for creating highly readable, self-documenting code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define and use union.
  • Understand how union shares memory between members.
  • Define and use enum to create readable constant values.
  • Know when to use struct vs. union.

3. Unions in C

A union is defined exactly like a struct. However, while a struct allocates separate memory for *every* member, a union allocates just enough memory to hold its *largest* member. All members share this single memory location.
c
1234567891011121314151617
#include <stdio.h>
#include <string.h>

union Data {
    int i;       // 4 bytes
    float f;     // 4 bytes
    char str[20];// 20 bytes
};

int main() {
    union Data data;
    
    printf("Memory size occupied by data: %lu\n", sizeof(data)); 
    // Output is 20, because str[20] is the largest member.

    return 0;
}

4. The Catch with Unions

Because all members share the same memory, you can only use ONE member at a time. If you assign a value to one member, the others are overwritten (corrupted).
c
12345678910
union Data data;

data.i = 10;
data.f = 220.5; // This overwrites the '10' !
strcpy(data.str, "C Programming"); // Overwrites the float !

// This will print garbage for 'i' and 'f' because the memory now holds a string
printf("data.i : %d\n", data.i);
printf("data.f : %f\n", data.f);
printf("data.str : %s\n", data.str); // Only this prints correctly

5. Why Use Unions?

Unions are heavily used in Embedded Systems where memory is incredibly scarce (e.g., an 8-bit microcontroller with 2KB of RAM). If you have a sensor that can return an integer, a float, OR a string (but never all three at once), a union saves memory.

6. Enumerations (enum)

An enum (enumeration) is a user-defined data type that consists of integral constants. It is used to make code more readable.
c
1234567891011121314
#include <stdio.h>

// By default, Sunday = 0, Monday = 1, etc.
enum Weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main() {
    enum Weekday today = Wednesday;

    if (today == Wednesday) {
        printf("It&#039;s hump day! (Value: %d)\n", today); // Prints: (Value: 3)
    }

    return 0;
}

7. Customizing Enum Values

You can manually assign integer values to enums.
c
12345678
enum Status {
    SUCCESS = 200,
    NOT_FOUND = 404,
    SERVER_ERROR = 500
};

enum Status api_status = NOT_FOUND;
printf("Status Code: %d\n", api_status); // Prints 404

8. Memory-Level Explanation

  • Union: The compiler finds the largest member (e.g., 20 bytes) and allocates exactly 20 bytes. All pointers to members &data.i, &data.f, &data.str point to the *exact same memory address*.
  • Enum: The compiler treats enums as standard integers (int), allocating 4 bytes. Enums don't save memory; they save developer sanity by replacing "magic numbers" with readable text.

9. Common Mistakes

  • Trying to use a union like a struct: Assigning values to all members of a union and expecting them to stay intact.
  • Putting strings in enums: enum Colors { "Red", "Blue" }; is illegal. Enums ONLY map text to integers, not to string literals.

10. Exercises

  1. 1. Create a union that can hold a character, an integer, or a double. Verify its size using sizeof.
  1. 2. Create an enum for the months of the year. Assign January to 1, so December naturally becomes 12. Write a program to print the value of August.

11. MCQ Quiz with Answers

Question 1

In a union, memory is allocated based on:

Question 2

What happens if you assign a value to union_var.b after assigning a value to union_var.a?

Question 3

The enum keyword is used to create:

Question 4

If enum Days {MON, TUE, WED};, what is the value of WED by default?

Q5. Can you assign specific integer values to enum constants? a) Yes b) No Answer: a) Yes
Question 6

Which data type does an enum resolve to under the hood in C?

Question 7

When should you use a union instead of a struct?

Q8. Are all members of a union stored at the same memory address? a) Yes b) No Answer: a) Yes
Question 9

Which operator is used to access union members?

Question 10

What is a "magic number" in programming?

12. Interview Questions

  • Q: Explain the exact difference in memory allocation between a struct and a union.
  • Q: Why are enumerations preferred over #define macros for defining state constants?

13. Summary

Unions group variables but share the same memory space, making them highly memory-efficient when only one variable is needed at a time. Enumerations (enum) assign human-readable names to integer constants, making complex logic (like state machines or status codes) much easier to read and maintain.

14. Next Chapter Recommendation

In Chapter 17: File Handling in C, we will learn how to save our program's data permanently by writing to and reading from text files on the hard drive.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·