(K&R Section 6.8 - Unions)
In the example:
To declare:
Code:
union u_tag {
int ival;
float fval;
char *sval;
} u;
And to use:
"If the variable utype is used to keep track of the current type stored in u, then one might see the code such as"
Code:
if (utype == INT)
printf("%d\n", u.ival);
if (utype == FLOAT)
printf("%f\n", u.fval);
if (utype == STRING)
printf("%s\n", u.sval);
else
printf("bad type %d in utype\n", utype);
For once I thought unions is a C feature, like in other languages I know such as perl, that makes it no longer a requirement to declare a variable to be of a particular type (whether it is an int, character, or a float, simply declaring "my variable;" in perl would work.
Another description is "Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program". I would assume this has something to do with whether an integer in a particular machine would occupy 16 or 32 bits.
So for the above example using the union "u" I thought this is the way I'd use it:
Code:
#include <stdio.h>
main()
{
int x = 1;
int y = 2;
union u_tag {
int ival;
float fval;
char *sval;
} u;
u.ival = x + y;
u.fval = x + y;
printf("%d\n", u.ival);
printf("%1.2f\n", u.fval);
Hoping I would get:
3
3.00
Surprisingly, the first printf didn't even print what I was expecting, instead gave me:
1077936128
3.00
What's up with that 1077936128??
Can anyone kindly give me a more layman's usage of unions?
What about those "utype == XXX" expression? INT, FLOAT, and STRING are macros, right? Macros for what numbers?
All I know is that unions are like structures, only that unlike structures, the members must be located in on particular place in the memory, and cannot have more than 1 variable of a particular type.