MCS-201 · Unit 6

Structures and Unions

Section 5 of 5

Block 2 · Unit 6Structures and Unions12 min · Section 5 of 5

6.5Unions

Covers IGNOU MCS-201 §6.7, 6.8, 6.9

Sometimes a variable must hold a value that is one of several types, but only one at a time: a payment that is either a card number or a cheque number, for example. A structure would reserve space for all the alternatives. A union reserves space for only the largest, and all its members share it.

What a union is

Syntax
union tag {
    data-type member1;
    data-type member2;
    ...
};

A union is declared and accessed exactly like a structure (with the dot operator), with the keyword union instead of struct. Storing a value in one member overwrites whatever was in the others.

Memory of struct s { int x; char y; float z; } and union u { int x; char y; float z; }
struct s:  | x x x x | y . . . | z z z z |     12 bytes: each member has its own place
union u:   | x x x x |                          4 bytes: x, y and z all start here

Declaring, initialising and accessing a union

  • A union can be initialised in its declaration, but the brace list sets only its first member: union temp t = { 65 };. Since C99, another member can be named: union temp t = { .z = 3.5f };.
  • The member written most recently is the one that should be read. Reading a different member reinterprets the same bytes as another type, which usually gives a meaningless value.

A union with a structure inside

Two views of the same bytes can be useful. In the study material’s date example, a 9-character date string and a structure that splits it into parts share the same storage:

C · union_date.c
#include <stdio.h>

union date_tag {
    char complete_date[9];
    struct part_date_tag {
        char month[2];
        char break_value1;
        char day[2];
        char break_value2;
        char year[2];
    } part_date;
};

int main(void)
{
    union date_tag date = { "01/12/05" };

    printf("Complete: %s\n", date.complete_date);
    printf("Month: %.2s  Day: %.2s  Year: %.2s\n",
           date.part_date.month, date.part_date.day, date.part_date.year);
    return 0;
}
Output
Complete: 01/12/05
Month: 01  Day: 12  Year: 05

The initialiser fills the first member, complete_date. The structure member overlays the same characters, so its two-character fields pick out the month, day and year. They are not null-terminated strings, so they are printed with a precision: %.2s.

Structure versus union

AspectStructureUnion
Keywordstructunion
MemoryEach member has its own storageAll members share the same storage
SizeAt least the sum of the membersAt least the largest member
Members valid at one timeAllOnly the one stored last
InitialisationAll membersThe first member only (or one named member)
Changing one memberDoes not affect the othersOverwrites the others
Typical useA record with several fieldsA value that may be one of several types; saving memory

Key takeaways

  • A union’s members share the same memory; its size is that of the largest member (plus padding).
  • Only the most recently stored member is valid.
  • Brace initialisation sets the first member only.
  • Structures store all members separately; unions store one at a time.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

On a system where int is 4 bytes and double is 8 bytes, what is the size of union u { char c; int i; double d; };?

Show answer

Answer: D. 8

A union is as large as its largest member, the 8-byte double. 13 is the sum, which applies to neither a union nor (because of padding) a structure.

Question 2 · multiple choice

How many members of a union hold valid values at the same time?

Show answer

Answer: A. One

The members share storage, so only the one stored most recently is valid.

Question 3 · multiple choice

What does union temp t = { 65 }; initialise, for union temp { int x; char y; float z; };?

Show answer

Answer: C. The first member, x

A brace initialiser without a member name sets the first member of a union.

Question 4 · multiple choice

What does this program print?

C · union_overwrite.c
#include <stdio.h>

union val { int i; char c; };

int main(void)
{
    union val v;
    v.i = 0;
    v.c = 'A';
    printf("%c\n", v.c);
    return 0;
}
Show answer

Answer: D. A

c was stored last, so reading c gives ‘A’. The earlier value of i has been partly overwritten.

Question 5 · multiple choice

Which statement about structures and unions is correct?

Show answer

Answer: B. A structure stores all its members; a union stores one at a time in shared storage

Separate storage is the property of a structure; shared storage is the property of a union, which is therefore never larger than the equivalent structure.

Question 6 · short answer

For members char name[20]; int id; float salary; (4-byte int and float), find the size of a structure and of a union with these members, and explain the difference.

Show worked answer

Structure: each member has its own storage, so the size is 20 + 4 + 4 = 28 bytes (no padding is needed, since 20 is a multiple of 4). Union: all members share one block as large as the largest member, name, so the size is 20 bytes. The structure can hold a name, an id and a salary at the same time; the union can hold only one of them at any moment, and storing a new member overwrites the previous one.

↑ ↓ move↵ openTab switch type