Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Question about unions in C language

Status
Not open for further replies.

impakt

Member level 4
Joined
Dec 19, 2005
Messages
68
Helped
2
Reputation
4
Reaction score
0
Trophy points
1,286
Activity points
1,799
Hello all,
suppose we have this union:
Code:
Union myunion
{
int i;
double d;
char c;
}mu 
sizeof(myunion)->8
sizeof(mu.i)->2
sizeof(mu.d)->1
sizeof(mu.c)->8
If the compiler allocates 8 bytes for this union, what happens when we want to compare 2 members of this union (meaning mu.d and mu.i)??
 

C language - unions

AA,
A union differs from a structure. A union is a common storage for different data types. In your example, you can use it as an integer or double or a character at a time.
BR,
Amr Ali.
 

Re: C language - unions

amraldo said:
AA,
A union differs from a structure. A union is a common storage for different data types. In your example, you can use it as an integer or double or a character at a time.
BR,
Amr Ali.

Hmm...
If the size of this union is 8, there's enough space to hold tha value of "d". Right?
What about "i" than? Where is it held if all the space is occupied by "d" (which is 8 )???
 

Re: C language - unions

AA,
Only 2 bytes are taken, the others take garbage value.
BR,
Amr ALi.
 

Re: C language - unions

I assume you switched the sizes of mu.d and mu.c: 8 and 1 respectively.

If you do

Code:
if( mu.d == mu.i) { code... }

then the compiler will read the 2 first bytes of mu, interpret them as an integer, read the 8 bytes of mu and interpret them as a double precision floating point number, and then do the comparison. If you're lucky and they are special values (zero?) you might have a chance that they match. But of course this can never be the intended use of an union. You always use a union ONE MEMBER at a time: you have to keep track what's contained at a certain moment and only use it that way.
 

C language - unions

I suggest reading the assembly code which is clear.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top