From the course: C: Data Structures, Pointers, and File Systems

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Understanding a union

Understanding a union - C Tutorial

From the course: C: Data Structures, Pointers, and File Systems

Start my 1-month free trial

Understanding a union

- [Narrator] A union is one of those funky C Language tools seldom used and rarely understood. It's related to a structure, sort of like a structure with an added level of flexibility, but it comes with a warning. First, let me demonstrate a type of union which you see here, declared in this coded line five. The union is named storage, and at line eight, a variable reg is created of these storage union type. Yes, it looks a lot like a structure, but it's two members to find that lines six and seven character a and integer b, they share the same storage space. They are not discrete values. Now in the rest of the code, character a is assigned the member reg.a, which you see used at line 10, and then at line 13, a value is assigned to member reg.b. So far, the union looks like a structure. In fact, if you changed union to structure at line five, the code would still work, but it's not a structure. Build and run. And you see the values of each member displayed in the output. In this…

Contents