what is the use of unions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

14th Nov 2019, 7:36 PM
PQV
3 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.
15th Nov 2019, 3:27 AM
Schindlabua
Schindlabua - avatar
+ 4
Not used much when you have plenty of memory and your data structures are small.
15th Nov 2019, 2:51 AM
Sonic
Sonic - avatar
+ 2
Bit like car sharing, hm?
14th Nov 2019, 11:12 PM
HonFu
HonFu - avatar