Hi All,
have some experience in C prog language. I have small doubt abt
using unions in C language.
Here is a small programm in vc++:
union a{
int b;
char c;
}d;
int main () {
As Twink would say: "Oh dear, you've done it now..."
d.b=360;
d.c=1;
printf("%d %d ",d.b ,d.c,);
}
In union largest sized member memory is reserved by union .
but for a sake if i declare this way then i've seen the d.b value is
showing 257 in output window and if i declare d.b =255 or below 255
that then it is showing the what is last defined for d.c, means value
is =1 for all variables.
So Here for first time how the memory is overwritten?
Your description of the output suggests that your machine stores data
in little-endian order. Let's see how the union is stored, assuming
that 'int's occupy four bytes:
____________________________________________________
| | |
| Member | Bytes |
|________|___________________________________________|
| | | | | |
| .b | 00000000 | 00000000 | 00000000 | 00000000 |
|________|__________|__________|__________|__________|
| | | | | |
| .c | 00000000 | | | |
|________|__________|__________|__________|__________|
That would be the union set to all-bits-zero. Now, when the statement
'd.b = 360;' is executed, the union will look like this:
____________________________________________________
| | |
| Member | Bytes |
|________|___________________________________________|
| | | | | |
| .b | 00000100 | 00000001 | 00000000 | 00000000 |
|________|__________|__________|__________|__________|
| | | | | |
| .c | 00000100 | | | |
|________|__________|__________|__________|__________|
The number 360 has the binary representation 100000100 (those are 9
bits), which occupies more that one byte. Since the machine is little-
endian, the '1' bit at the left will appear as the right-most bit of
the "second byte".
And when the statement 'd.c = 1;' is executed, it will look like this:
____________________________________________________
| | |
| Member | Bytes |
|________|___________________________________________|
| | | | | |
| .b | 00000001 | 00000001 | 00000000 | 00000000 |
|________|__________|__________|__________|__________|
| | | | | |
| .c | 00000001 | | | |
|________|__________|__________|__________|__________|
The number 1 looks the same in decimal and in binary. So, the
statement 'd.c = 1;' has changed the first byte of d.b, but not the
second, which retains a '1' bit for its right-most bit.
At this point, d.b has the binary representation 100000001, and that's
why you're seeing 257 when you print d.b -- 100000001 is 257 in
decimal.
And the reason you get the "expected" values if you assign the number
255 or below to d.b is that 255 can be represented using only one byte
(255 is 11111111 in binary; any number higher than that would require
at least two bytes, and would mess up the union).
Sebastian