Learning that you can use unions in C for grouping things into namespaces

#78 · 🔥 167 · 💬 147 · 2 years ago · utcc.utoronto.ca · deafcalculus · 📷
Today's trick is using C unions to group struct fields together, which I learned about through this LWN article. You also want to keep simple field access and for people using your struct to not have to know that these fields in particular are special. One of the problems with this is the #defines, which have very much fallen out of favour as a way of renaming fields. What you do is that you embed two identical sub-structs inside an anonymous union, with the same fields in each, and give one sub-struct a name and keep the other anonymous. The anonymous sub-struct inside the anonymous union lets you access its fields without any additional levels of names. The non-anonymous struct lets you refer to the whole thing by name. Naturally people create #define macros to automate creating this structure so that all fields stay in sync between the two structs inside the union.
Learning that you can use unions in C for grouping things into namespaces



Send Feedback | WebAssembly Version (beta)