c – What are they and when to use Anonymous Unions?

Question:

While reading the data structure book, the concept of anonymous unions was briefly introduced, which would be the definition of a union without specifying a label (name). But I didn't understand what the use of this type of data is.

Is this definition correct?

When should I use this data type?

Answer:

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 you are going to declare a union that you will only use there and nowhere else so you don't need to create a type or a contract of what the type should look like in advance, just declare that it will be a union with those characteristics and good.

It is more valid when used inside a struct , so instead of accessing a member of the struct that is a union and accessing the union member on that member, it already accesses the union member directly as if it were part of the struct , but like is a union the space will be occupied by only one of the members (largest). If these members were declared directly in the struct it would not be part of a union .

The usefulness is not great, but it is useful in some cases. Both ways:

#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);
} 

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

Scroll to Top