What are the advantages of using Unions?
|
Contributor
|
|
| 16May2008,17:50 | #1 |
|
What are the advantages of using Unions?
|
|
Go4Expert Founder
|
![]() |
| 16May2008,22:05 | #2 |
|
Save memory
|
|
Go4Expert Member
|
|
| 23May2008,15:44 | #3 |
|
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 |
|
Go4Expert Founder
|
![]() |
| 23May2008,15:53 | #4 |
|
Just checkout if this is true
sizeof(test_1) = 5 Because of packaging format it will be 8 ( assuming what you are assuming ) |
|
Go4Expert Member
|
|
| 23May2008,16:04 | #5 |
|
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. |
|
Light Poster
|
|
| 12Sep2009,11:32 | #6 |
|
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ?
seriously !!! Last edited by shabbir; 12Sep2009 at 18:39.. Reason: Font Size |
|
Go4Expert Founder
|
![]() |
| 12Sep2009,18:39 | #7 |
|
Mentor
|
![]() |
| 12Sep2009,22:51 | #8 |
|
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. |
|
Invasive contributor
|
![]() |
| 13Sep2009,01:39 | #9 |
|
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
|




