UPI Study › Courses › Programming in C › Free lessons › Lesson 10.6 Free with a free account
The Union Data Type in C
Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.6 · lesson 69 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Workshop: Modeling Real-World Entities with Structures and Unions →← Passing and Returning Structures in FunctionsNext lesson: Workshop: Modeling Real-World Entities with Structures and Unions →
In this lesson
Storing one of several values in shared memory with unions.
- Explain how a union's members share one location and how its size is set
- Compare the memory layout of a union and a struct with the same members
- Build a tagged union with an enum tag and read it through a switch
- Decide whether a struct or a union fits a set of values
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,047 words). Read along, or search it.
Opening Question
One Prize per Cabinet Slot
A prize cabinet at the Starlight Arcade holds one prize per slot: a pile of bonus tokens, or a toy, or a coupon. Never all three at once. So would you build every slot big enough for all three? C has a tool for one of these, but only one at a time: the union. It looks like a struct, but it behaves very differently.
Definition
Every Member Shares One Box
A struct gives every member its own box, side by side. A union gives every member the same box. You write it like a struct, but with the word union. Here, union Prize holds tokens, a discount, and a toy name. Below it, struct Box has the same three members. Build and run. The int is 4 bytes, the double is 8, and the toy name is 16. The union is only 16 bytes: the size of its biggest member. struct Box needs 32.
Memory Layout
Why the Union Needs Only 16 Bytes
Here's why. struct Box lays its members end to end. First, 4 bytes of tokens. Then 4 spare bytes, so the double starts at a multiple of 8. Then 8 for the double, and 16 for the toy: 32 in all. The union stacks all three on the same starting byte. So it needs only as much room as the biggest one: 16. A compiler may also add spare bytes at the end of a union. With a double inside, this Mac keeps the size a multiple of 8. 16 already is, so here none are needed.
Overlapping Members
Writing One Member Overwrites the Others
Because the members overlap, writing one member overwrites the others. Here Priya writes tokens, then reads tokens. She writes the discount, then reads it. Then the toy, the same way. Build and run: 50, 0.25, and Robot. Each read matches the write just before it, and that's always safe. The last line compares the addresses of tokens and toy. The answer, 1, means yes: the same spot.
Common Mistake
Reading a Member You Did Not Write
A union remembers nothing about which member you used last. It holds only bytes. So what if Priya stores the toy, and then reads tokens? She adds two lines: tokens, and the same value in hex. Build and run. No warning, and tokens is 1868722002. It's a number, but it means nothing as a token count. The hex shows why: 6f 62 6f 52. Read from the right, those are the bytes of R, o, b, o, the toy's first four letters. This Mac stores the low byte first, so another machine could print another number. Sam calls this the quietest bug in C: nothing complains. Reading the double right after storing tokens is no better: half its bytes were never written. The rule: read the member you last wrote.
Quick Check
Sizing a Union With a Double Inside
Quick check. A ticket union holds either a code of 20 characters, or a price as a double. How many bytes is one union Ticket, on this Mac? Pause and predict. Build and run: 24. The biggest member is the 20-character code. But with a double inside, this Mac keeps the union's size a multiple of 8. So 4 spare bytes go at the end, making 24. 20 forgets those bytes, and 28 adds the members up, which a union never does.
Tagged Union
An Enum Tag Records the Live Member
So how can a program know which member is live? Keep a note next to the union. That note is called a tag. The tag is usually an enum: a type that gives names to a short list of whole numbers. Here PRIZE_TOKENS is 0, PRIZE_TOY is 1, and PRIZE_DISCOUNT is 2. Enum names count up from zero. struct Prize holds the tag, called kind, and then the union. That union has no name of its own: it's declared as the member data. Tag plus union: that pair is called a tagged union.
Worked Example
Switching on the Tag to Show a Prize
show_prize switches on the tag, so it only ever reads the member that matches. For a toy, it reads p arrow data dot toy. The union sits inside the struct, so you go through data first. In main, braces with dot tokens equals 25 fill one member by name. That also tells C which member you mean. Whenever you store a prize, you set its tag too. Each prize on this shelf gets its tag first. Build and run: 25 bonus tokens, a Robot toy, and 20 percent off the snack bar. And one Prize takes 20 bytes: 4 for the tag, and 16 for the shared data.
Quick Check
A Wrong Tag Misreads the Data
Quick check. This prize is stored as a 35 percent discount. Then one line changes only its tag, to PRIZE_TOKENS. show_prize is the same as before. What does this program print? Pause and predict. It prints 35 bonus tokens. The switch trusts the tag, so it reads data dot tokens. And tokens and percent share the same four bytes, so the 35 shows up as tokens. The union can't object, and neither can the compiler. Keeping the tag honest is your job: set it whenever you store a member.
Compiler Help
Clang Warns About Missing Enum Cases
One more safety net. Priya adds a fourth kind, PRIZE_PASS, to the enum, but forgets to add it to the switch. Build it. Clang warns: enumeration value PRIZE_PASS not handled in switch. Its note says: add missing switch cases. Clang gives this warning even without dash W all. So a new kind points you to every switch that needs a case. Add the missing case, and the warning goes away. A union without a tag is a trap waiting for a tired programmer.
Decision Guide
Struct or Union
So, struct or union? Ask one question: do I need all these values at the same time? A player has a name and a score together. That's a struct. A prize is tokens, or a toy, or a discount, one at a time. That's a union, usually wrapped with a tag. Unions save memory, which matters when you have thousands of records. But they make you do the remembering. So when in doubt, use a struct. Reach for a union only when exactly one of the values is ever in use.
Key Takeaways
Shared Memory and Honest Tags
To sum up. A union's members all share one spot in memory. Its size is its largest member's, plus any spare bytes at the end. Read only the member you last wrote. C won't stop you if you don't. And a tagged union pairs an enum tag with the union, so a switch can read the right member.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About The Union Data Type in C
What is the difference between a struct and a union in C?
How big is a union in C?
What happens if you read a different union member than the one you wrote?
What is a tagged union in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →