For example,
union { float fl, unsigned int uinteg, char ch, int integ } foo; All this is stored alternately in one area of memory. What's the point, because once you set the values
foo.fl = 3.14f; foo.uinteg = 666; foo.ch = 'a'; foo.int = -25; it won't be possible to get them back - will everything get mixed up? A way to save a couple of bytes or a couple of clocks and at the same time save readability? Not to write 4 different functions, but to write one that takes the union and already decide what to do? In this case, isn't it easier to accept void * and then cast into the type you need? As an example, "Just cast" I will give this code:
Classic example:
typedef enum { STR, INT } tType; typedef struct { tType typ; // typ is separate. union { int ival; // ival and sval occupy same memory. char *sval; }; } tVal; void printer(tVal uni) { if (uni.type == INTEGER) // blah-blah uni.ival // Используем integer else ini.sval // В противном случае } The function of the printer can be rewritten something like this:
void printer(void* data, tType typ) { if (tType == INTEGER) { (int*)data // Чего-то делаем } } Another example:
union { int a; int b; int c; } bar; bar.a = 20; bar.b = 50; // Значение a потеряли :( Again, what's the point if I can first get a separate variable int a = 20; and then change its value a = 50; and the effect is exactly the same? Looks like a strong witchcraft.