What are they and when to use Anonymous Unions?

Asked

Viewed 128 times

14

During the data structure book reading, it was briefly presented the concept of anonymous unions, which would be the definition of a union without specifying a label (name). However, I did not understand the usefulness of this type of data.

This definition is correct?

When should I use this kind of data?

2 answers

9


I imagine you know what a normal union is. Well, the anonymous one doesn’t have a name, so the only way to access it is through its members.

This is useful when it will declare a union that will only use there and nowhere else then it does not need to create a type or a contract as it should be kind of early, only declares that it will be a union with those characteristics and good. It is more valid when it is used within a struct, so instead of accessing a member of struct which is a union and in that member access the union member, already access the union member directly as if he were part of the struct, but how is a union the space occupied will be only one of the members (the largest). If these members were declared direct on struct would not be part of a union.

The utility is not great, but is useful in some cases. The two forms:

#include<stdio.h>

typedef struct {
    union {
        char c;
        int i;
    };
} Tipo;
  
int main() {
    union {
        char c;
        int i;
    } x;
    x.i = 65;
    Tipo y;
    y.i = 65;
    printf("%c, %c", x.c, y.c);
} 

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

Just to show an example that I find useful, imagine that you have a structure (vector) that represents coordinates in 3 three dimensions (x, y, z). But you also need a structure that represents colors, and also has three variables (red, green, blue). The structure of the colors and the vector are very similar, what changes is just the name of the member variables. In addition, Voce already has a wide range of vector manipulation functions, and it would be very useful if Voce also had them for the color structure. To solve your problem you could do the following:

struct vec3{
    union{
        struct{
            float x, y, z;
        };

        struct{
            float r, g, b;
        };
    };
};

using color = vec3;

And if you have for example a function that normalizes a vector you can also use to normalize the colors, without having to redefine the function.

But of course you could also define the structure vec3 only with the variables x, y and z, and use for the two tasks. But I think that this way the code becomes more natural.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.