The Union Data Type in C, Explained with Code Examples

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

← Passing and Returning Structures in FunctionsNext lesson: Workshop: Modeling Real-World Entities with Structures and Unions →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A struct gives every member its own space, so all the values exist at once, while a union places every member at the same starting address, so only one value is meaningful at a time. With an int, a double, and a 16-character array as members, a union took 16 bytes on one Mac, but a struct with the same members needed 32 because of padding.
How big is a union in C?
A union is as large as its biggest member, plus any padding the compiler adds at the end for alignment. A union holding a 20-character array and a double took 24 bytes on one Mac, not 20, because its size was rounded up to a multiple of 8 for the double. Adding the members together, 28 here, gives the wrong answer, so ask sizeof.
What happens if you read a different union member than the one you wrote?
You get the stored bytes reinterpreted as the other type, with no error or warning. After storing the text Robot and reading an int member, one Mac printed 1868722002, which is simply the bytes of R, o, b, and o read as a little-endian number. The value means nothing and may differ on another machine. The safe rule is to read the member you last wrote.
What is a tagged union in C?
A tagged union pairs an enum tag with a union inside a struct, so the program records which member is currently live. A switch on the tag then reads only the matching member, such as p->data.toy when the kind is PRIZE_TOY. The tag must be set every time a member is stored. Clang also warns when a switch on the enum has no default label and misses a value, such as a newly added kind.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →