-
Union declaration
Q1.
Code:
union uv
{
unsigned long vol;
unsigned char vol_bricks[4];
};
xdata union uv xv[3];
Is the above declaration "union uv xv[3];" valid??
Can I declare array of unions as above??
:(
2)
Code:
void f1()
{
union uv biggest_value;
xv[0].vol = value0;
xv[0].vol = value0;
xv[0].vol = value0;
biggest_value.vol = xv[0].vol;
if( biggest_value.vol_bricks[0] < xv[1].vol_bricks[0] )
biggest_value.vol = xv[1].vol;
if( biggest_value.vol_bricks[0] < xv[1].vol_bricks[0] )
biggest_value.vol = xv[1].vol;
Global_value = biggest_value.vol;
}
HERE:
"if( biggest_value.vol_bricks[0] < xv[1].vol_bricks[0] )"
"if( biggest_value.vol_bricks[0] < xv[1].vol_bricks[0] )"
these "if" statements are observed, they are never true.
Is there any error in declaration?
Is the way "character item 0" in the unoins are compared causing any problem?
3.I require guidance regarding usage of UNION.
-
Code:
xv[0].vol = value0;
xv[0].vol = value0;
xv[0].vol = value0;
These lines are all redundant. You only need one. The same goes for your if check. There's no point in having more than one.
Aside from the xdata portion you have typed in there, sure, it's correct. This is perfectly valid, and will declare an array of unions:
Code:
union foo
{
...some stuff...
};
union foo bar[5]; /* create an array, called bar of 5 'foo' unions. */
You can compare and use union members the same way you would use struct members. If you know how to use a struct, you know how to use a union. The only difference is that all members of the same union share the same space in memory. If you change the value of one member, it affects them all.
Code:
union foo
{
char c;
int i;
double d;
float f;
};
union foo bar;
bar.c = 'a';
Now you've just modified all members of the union, since they share the same space in memory.
Quzah.