Deep C Dives: The Union |
Written by Mike James | |||||||
Wednesday, 29 January 2025 | |||||||
Page 3 of 3
Tagged UnionAlthough 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 ThoughtsUnions 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
|
.NET Aspire 9.3 Adds New Lifecycle Events 22/05/2025 .NET Aspire 9.3 has been released with improvements including the addition of GitHub Copilot to the .NET Aspire dashboard, along with a new context menu in the Resource Graph view; and new lifecy [ ... ] |
AI Highlights From Google I/O 2025 22/05/2025 At Google I/O, Sundar Pichai, Demis Hassabis and others took to the stage to outline a long lineup of AI-powered products and services including Gemini 2.5, AI Mode in Search, which is already b [ ... ] |
More News
|
Comments
or email your comment to: comments@i-programmer.info