From last week’s Lesson, you saw an example of how different data types stored in a union can be beneficial. As both structures WORDREGS and BYTEREGS overlapped to reflect the data stored in an 8086 CPU, using a union to represent the data is both practical and economic. But such conditions are rare.
The union in the following code holds two 8-byte chunks of data. One is identified as a string (or character aarray) and the other as a long integer.
2026_10_03-Lesson-a.c
#include <stdio.h>
int main()
{
union text {
char ch[8];
long li;
} t;
t.li = 0xA216F6C6C6548;
printf("%s",t.ch);
return 0;
}
The text union t stores string ch and long int li. The value of t.li is assigned 0xA216F6C6C6548. But the printf() statement outputs string ch, which is based on the data stored in t.li. Here’s the program’s output:
Hello!
The value of t.li is equal to the ASCII codes for the text stored in string ch. This relationship may not be immediately apparent as the characters are read in reverse order, which is the way values are stored byte-wise inside the computer:
00 = null character
0A = newline
21 = ‘!’
6F = ‘o’
6C = ‘l’
6C = ‘l’
65 = ‘e’
48 = ‘H’
Now consider this code:
2026_10_03-Lesson-b.c
#include <stdio.h>
int main()
{
union text {
char ch[8];
long li;
} t;
t.li = 0xA216F6C6C6548;
printf("%s",t.ch);
t.li -= 0xAFFF9F5F1;
printf("%s",t.ch);
return 0;
}
In this update, the value 0xAFFF9F5F1 is subtracted from t.li. The result is output as another string:
Hello! World!
The result is amusing, but consider how the data modified in of one type but affects the other type. This relationship shows the danger of using a union to store data, especially unrelated data. Even when the motive in intentional and the data types are related to each other in some way, the results can be unpredictable. But there is a solution.
The answer is to tag a union. I cover this process in next week’s Lesson.