Where do we use/need union? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Where do we use/need union?

Okay, so union is a data type which can store different types of data but only one member can contain a value at a time.

26th Apr 2018, 1:31 PM
Cyan
Cyan - avatar
7 Answers
+ 9
Unions allow quick conversion between data making use of addressable units. Usually, all members contain a single value at the same time. I've used a compiler where each bit was individually assignable to a field so converting to binary was as simple as put the integer in the union and print out the array of bits from the union. In compiler writing, it makes putting instructions together simple. You can write the individual bytes to the binary object file. Treat addresses as a multibyte units, etcetera. However, in the normal day in and day out programming, it doesn't serve a purpose because that type of low level conversion isn't required.
26th Apr 2018, 4:39 PM
John Wells
John Wells - avatar
+ 9
https://www.crazyengineers.com/threads/use-of-unions-in-c.21703/ refer the above link Union was used in older days when main memory size was small.
26th Apr 2018, 4:39 PM
Rstar
Rstar - avatar
+ 7
Here an useful example to convert color bytes into the integer needed to set a color. https://code.sololearn.com/cHywd0RPiIP4
26th Apr 2018, 5:05 PM
John Wells
John Wells - avatar
+ 2
John Wells Thank you sir
26th Apr 2018, 5:33 PM
Cyan
Cyan - avatar
0
I'm not familiar with this topics
26th Apr 2018, 4:41 PM
Mohammad Ismail
Mohammad Ismail - avatar
0
we need union when we work with same kind of tables...having same column names with same data types.
13th May 2018, 7:53 AM
Mohan Negi
Mohan Negi - avatar
0
we need union when we work with recursive query. example: hierarchical data such country and cities relationship
5th Jun 2018, 11:28 AM
amin chegeni zadeh
amin chegeni zadeh - avatar