Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This
Like this article? We recommend

Union Types

Often, you’re likely to want to access individual elements of a vector. So far, when we’ve wanted to do that we’ve cast a pointer to the vector, to a pointer, to an integer, and used it as an array. While this technique works, it’s very messy. We can improve on it somewhat by using union types, like this:

typedef union
{
  v4si v;
  int s[4];
} vector;

This is one of the very few sensible uses for a union. Often, unions lead to bugs because you have to keep track manually of what kind of data is stored in the union. Here, however, the same kind of data is stored, no matter how you access it. Now we can do vector operations by using the .v part of the union, and scalar operations using the .s part. union.c (included in the source.zip file for this article) contains our first example, rewritten to use a union. Hopefully, it’s much easier to read.

Don’t forget that even though the syntax for accessing the components is now quite clean, it’s still a very expensive operation. Most vector units lack a "store this element in an scalar register" instruction, so you need to write the vector to memory (or, at least, cache) and then read it back in.

  • + Share This
  • 🔖 Save To Your Account