Deep C Dives: The Union
Written by Mike James   
Wednesday, 29 January 2025
Article Index
Deep C Dives: The Union
Color
Tagged Union

Tagged Union

Although the main use of unions in low-level C programming is to perform type punning, this is not what more general programmers tend to think a union is for. Many programmers, and especially those more familiar with higher-level languages, see unions as ways of saving storage or creating flexible data structures often called variants or tagged unions.

For example, suppose you have a name record which sometimes has a telephone number as a string and sometimes as an integer. You could store this as:

struct {
        int type;
        union {
            char numstring[10];
            int numint;
        } phone;
} person;

Notice that the phone fields are a union of char[10] and int. The type field is the tag indicating which type is to be used. For example:

person.type = 1;
strcpy(person.phone.numstring,"1234");
person.type = 0;
person.phone.numint = 1234;

When trying to access the fields you would test the type field first.

In this example, it is obvious that you should parse the variations on the telephone field into a standard format, but there are situations where this doesn’t make sense.

If the compiler supports anonymous unions we can get rid of the phone field which seems unnecessary:

struct {
        int type;
        union {
            char numstring[10];
            int numint;
        };
} person;

Now we can write:

person.type = 1;
strcpy(person.numstring, "1234");
person.type = 0;
person.numint = 1234;

GCC supports this use of an anonymous union.

Final Thoughts

Unions are the preferred way of type punning mainly because they have to be explicitly declared. If you want to alias two types then you have to create a union that implements this. If you use casting then you don’t have to prepare in advance, you can simply cast as needed. This makes it harder for the compiler to detect when you use an alias.

Deep C Dives
Adventures in C

By Mike James

Cdive360

Buy from Amazon.

Contents

Preface
Prolog C
Dive

  1. All You Need Are Bits
  2. These aren’t the types you’re looking for
  3. Type Casting
  4. Expressions
  5. Bits and More Bits
        Extract:
    Bits!
  6. The Brilliant But Evil for 
  7. Into the Void 
  8. Blocks, Stacks and Locals
  9. Static Storage
  10. Pointers
  11. The Array and Pointer Arithmetic
  12. Heap, The Third Memory Allocation
  13. First Class Functions
        Extract:
    First Class Functions
  14. Structs and Objects
        ExtractValue Structs ***NEW!
  15. The Union
  16. Undefined Behavior
  17. Exceptions and the Long Jump

<ASIN:B0D6LZZQ8R>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Facebook or Linkedin.

Banner


AI - It's All Downhill From Here?
31/12/2025

AI is a complex beast, but it is based on some very simple and very powerful ideas that deserve to be better known as they throw much light not only on the way AI works but on the way the universe wor [ ... ]



The Thinking Game
04/01/2026

If you haven't already watched it, The Thinking Game is a fascinating and inspirational video. It tells the inside story of how Deep Mind, led by Demis Hassabis, produced AlphaFold and what this break [ ... ]


More News

pico book

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Wednesday, 09 April 2025 )