+ 1
what is the use of unions
Can domebdy explain me what the use of unions is? I don't get why I would use them, since it can only store 1 variable at the time. Why would I use them instead of structures?
4 Answers
+ 5
We can also use them to represent a choice, or options.
Imagine you are making a game, and the player can either be a human, orc, or elf:
typedef struct { ... } human;
typedef struct { ... } orc;
typedef struct { ... } elf;
union player {
human h;
orc c;
elf e;
}
So a struct gives us a way to turn multiple types into one type and unions give us choice. Type theory says that's all we need to make any datatype we want to.
+ 4
Not used much when you have plenty of memory and your data structures are small.
+ 2
Bit like car sharing, hm?