Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   What are the advantages of using Unions? (http://www.go4expert.com/forums/advantages-using-unions-t10650/)

aspguy 16May2008 17:50

What are the advantages of using Unions?
 
What are the advantages of using Unions?

shabbir 16May2008 22:05

Re: What are the advantages of using Unions?
 
Save memory

atul.sharma12 23May2008 15:44

Re: What are the advantages of using Unions?
 
Let me explain you by an example..

struct test {
int temp1;
char temp2;
} test_1;

union test {
int temp1;
char temp2;
} test_2;

when you take the size of both then you will see the difference.
in case of structure sizeof(test_1) = 5 (I am taking the integer size as 4 bytes)
whereas in caes of union sizeof(test_2) = 4

In union the memory occupied by the largest data is being reused to store the other members of the union.In this case it happen to INT so the size came 4.

Hope it will make things more clear

shabbir 23May2008 15:53

Re: What are the advantages of using Unions?
 
Just checkout if this is true

sizeof(test_1) = 5

Because of packaging format it will be 8 ( assuming what you are assuming )

atul.sharma12 23May2008 16:04

Re: What are the advantages of using Unions?
 
I agree......
And I appreciate ur immediate concern.
Forgot the padding issue...Excatly the size will be 8 due to insertion of extra bytes by compiler.

Thank you once again for correcting me
and sorry for the mistake.

docesam 12Sep2009 11:32

Re: What are the advantages of using Unions?
 
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ?

seriously !!!

shabbir 12Sep2009 18:39

Re: What are the advantages of using Unions?
 
Quote:

Originally Posted by docesam (Post 57260)
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ?

seriously !!!

Bigger font does not speak more.

xpi0t0s 12Sep2009 22:51

Re: What are the advantages of using Unions?
 
The obvious example of a use for unions is a spreadsheet where a cell can contain a date, number, some text, a formula or other things depending on the design.

Another use of unions is to convert from one data type to another.

mayjune 13Sep2009 01:39

Re: What are the advantages of using Unions?
 
It can also be used where an application will be used where every byte used is important, like lets say if you are writting an application for a small calculator which has very less memory, now every byte here being used is very important! Hence, union will be prefered. There maybe other examples too like this one


All times are GMT +5.5. The time now is 16:00.