⚙️ C programming basics · Class 10 · Lesson 10 of 18 · Free
Unions & Enums in C – Named Constants and Shared Memory
⏱ About 30 minutes · ▶ run real C here — nothing to install · no sign-in
In this lesson you will
- Create an enum and use its names in place of magic numbers
- Write a switch on an enum value and print a readable name for it
- Explain how a union shares memory and build a tagged union with a struct
Your school canteen app stores the tiffin size as 0, 1 or 2. A month later, nobody remembers if 2 means small or large. In this lesson you give such numbers real names with enum, and you learn union, a box that holds one of several kinds of value.
What is an enum in C?
An enum (short for enumeration) is a list of names for whole numbers. You write the names once. C gives them the values 0, 1, 2 and so on.
Each name is a constant, so you cannot change it. The enum type itself is a new type name, like enum Size. Inside, it is just an int.
Why bother? `size == LARGE` tells the reader what you mean. `size == 2` does not. Try it: add EXTRA_LARGE after LARGE and print it.
SMALL = 0 MEDIUM = 1 LARGE = 2 Your tiffin is medium.
💡 Enum names are usually written in CAPITAL letters, like other constants.
How do you use an enum with switch in C?
A switch on an enum is very common. Each case uses a name, so the code reads like plain English.
Here each railway coach class has a fare per 100 km. The function `fare_per_100km` returns the fare for the coach you pass in.
Bonus: with warnings on (-Wall), clang warns you if you forget a case for one of the names. That catches bugs when you add a new name later. Try it: add a GENERAL coach to the enum and run again.
Fare for 300 km: Rs 480 Same trip in sleeper: Rs 180
💡 These fares are made-up numbers for practice.
How do you print the name of an enum value in C?
printf cannot print an enum's name. It only sees the number. The usual trick is an array of strings in the same order as the enum.
You can also choose the numbers yourself. Here JAN = 1, so FEB becomes 2 automatically. Each name without a value is one more than the name before it.
`typedef` (from Lesson 4) lets you write `Month` in place of `enum Month`. Try it: add APR to the enum, "April" to the names, one more paid value, and change the loop to end at APR.
FEB has the number 2 Fee month: February January paid February paid March NOT paid
💡 Index 0 of month_names is an empty string because no month has the number 0.
What is a union in C and how is it different from a struct?
A struct (Lesson 4) gives every member its own space. A union puts all members in the SAME space. So a union holds only one member's value at a time.
The size of a union is the size of its biggest member (plus some padding). That saves memory when you know you need only one of the values.
When you write a new member, the old value is gone. Try it: after setting `grade`, print `u.marks` again and see that it is no longer 85.
struct size: 16 bytes union size: 8 bytes marks = 85 grade = A
💡 Sizes are for this compiler. On other computers they can differ.
What is a tagged union in C?
A union does not remember which member you stored last. So programmers add an enum next to it, called a tag. The tag says which member is valid now.
Here a report card entry is either marks (a number), a grade letter, or ABSENT. The struct keeps the tag and the union together.
Always check the tag before you read the union. Try it: add a fourth subject that is GRADE with 'B'.
Maths 92 / 100 Art grade A Science absent
💡 `.marks = 92` is a designated initialiser: it says which union member gets the value.
🤔 Predict the output
Think like C: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
enum Level { LOW, MID = 5, HIGH };
printf("%d %d\n", LOW, HIGH);Question 2. On this compiler an int is 4 bytes and a double is 8 bytes. What does this print?
union Box { int n; double d; };
printf("%zu\n", sizeof(union Box));Question 3. What does this print?
enum Light { RED, YELLOW, GREEN };
enum Light now = GREEN;
now = now - 1;
if (now == YELLOW) printf("get ready\n");
else printf("stop\n");🧩 Your challenge
A kirana shop sells loose rice by pack size. Make `enum Pack { HALF_KG, ONE_KG, FIVE_KG };` and a function `int price(enum Pack p)` that returns 30, 55 and 260 rupees. Read 3 orders (each a number 0, 1 or 2) and print each pack's name and the total bill. Example for inputs 1, 2, 0: Order 1: 1 kg - Rs 55 Order 2: 5 kg - Rs 260 Order 3: 1/2 kg - Rs 30 Total: Rs 345
Pack code for order 1 (0-2): 1 Order 1: 1 kg - Rs 55 Pack code for order 2 (0-2): 2 Order 2: 5 kg - Rs 260 Pack code for order 3 (0-2): 0 Order 3: 1/2 kg - Rs 30 Total: Rs 345
⚠️ Common mistakes (and how to fix them)
❌ Wrong
union { int marks; char grade; } r;
r.marks = 85;
r.grade = 'A';
printf("marks %d, grade %c\n", r.marks, r.grade);
Compiles and runs, but prints: marks 65, grade A ⏎
✅ Right
struct { int marks; char grade; } r;
r.marks = 85;
r.grade = 'A';
printf("marks %d, grade %c\n", r.marks, r.grade);
A union keeps only ONE value. Writing grade overwrote part of marks, so marks is no longer 85. If you need both values at once, use a struct.
❌ Wrong
enum Day { MON, TUE, WED };
enum Day d = WED;
switch (d) {
case MON: printf("Maths test\n"); break;
case TUE: printf("Sports day\n"); break;
}
Line 3: warning: enumeration value 'WED' not handled in switch [-Wswitch]
✅ Right
enum Day { MON, TUE, WED };
enum Day d = WED;
switch (d) {
case MON: printf("Maths test\n"); break;
case TUE: printf("Sports day\n"); break;
case WED: printf("Library period\n"); break;
}
The switch forgot WED, so nothing is printed for Wednesday. Clang warns you about the missing name. Read warnings: they often point at real bugs.
❌ Wrong
enum Tiffin { SMALL, LARGE };
enum Cup { SMALL, BIG };
printf("%d\n", LARGE + BIG);
Line 2: error: redefinition of enumerator 'SMALL'
✅ Right
enum Tiffin { TIFFIN_SMALL, TIFFIN_LARGE };
enum Cup { CUP_SMALL, CUP_BIG };
printf("%d\n", TIFFIN_LARGE + CUP_BIG);
All enum names share one space in a C file. Two enums cannot both use SMALL. Add a prefix such as TIFFIN_ to keep names unique.
📌 Remember
- An enum gives names to whole numbers; they start at 0 unless you set a value.
- A name without a value is one more than the name before it.
- Use an array of strings to print an enum value's name.
- A union stores all members in the same space, so it holds one value at a time.
- A union's size is the size of its biggest member (plus padding).
- A tagged union is a struct with an enum tag and a union; check the tag before reading.
Finished the quiz and the challenge?
Questions students ask
What is the difference between enum and #define in C?
Both give names to numbers. An enum groups related names into one type, numbers them for you, and the compiler can warn about missing switch cases. #define is a plain text swap done before compiling, with no type.
Can an enum variable hold a number that is not in the list?
Yes, in C it can. `enum Size s = 7;` compiles, because an enum is just an int inside. C does not check it for you, so check the range yourself when the number comes from input.
When should I use a union in C?
Use a union when a value can be one of several types, but never two at once. Examples are messages in a network protocol or tokens in a calculator. Pair it with an enum tag so you know which member is valid.
What is the size of an enum in C?
Usually the same as an int: 4 bytes on this compiler. The C standard lets compilers pick a smaller or larger integer type, so check with sizeof if it matters.