Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I wanna ask these code :
C++
#include <stdio.h>

union MyUnion
{
	int iVal;
	float fVal;
	char cVal[5];
	//char c[9];
};

void main()
{
	union MyUnion u={10};
	u.fVal = 100;
	printf_s("%d\n%f\n%d\n%d\n", u.iVal, u.fVal, u.cVal[0], 
		sizeof(u)); 
	getchar();
}


The output was this like :
VB
1120403456
100.000000
0
8


But I think in the line of
C++
void main(){
union MyUnion u={10};
..
..
}
, I'd declared that first union member is 10.
Why it doesn't?

Thanks in advances
Posted
Comments
CPallini 18-Apr-12 4:05am    
Because it is a union. Check out the documentation!

The intent of a union is overlay all members in the same storage space. This is usually done if only one of the members gets assigned a value at a time.

When you assigned 100.0 to u.fVal you thereby reused the storage of iVal and overwrote the 10 that was in there. What you later see in iVal is the floating point formatted value of fVal, interpreted as an int.

If you don't want that behaviour of multiple members sharing the same space, then use struct instead of union.
 
Share this answer
 
Comments
Shmuel Zang 18-Apr-12 2:59am    
5'ed.
nv3 18-Apr-12 3:44am    
Thanks!
You have used a union where, I think, you actually want a structure. See here[^] for more information.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900