简体   繁体   中英

Why the value of x and y is 1

union test{  
    unsigned int x: 3; 
    unsigned int y: 3; 
    int z;}; 
int main(){      
 union test t;   
 t.x = 5;  
 t.y = 4;   
 t.z = 1; 
 printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);  
 return 0;
}

I can not understand why the value of x and y is 1, any help is appreciated thanks .

EDIT: thanks all of you for the inputs ,you have asked for outputs I don't have a compiler at present anyway way i compiled the code online and these are the outputs

for z= 1  :      t.x = 1, t.y = 1, t.z = 1

for z= 2  :      t.x = 2, t.y = 2, t.z = 2

for z= 10 :      t.x = 2, t.y = 2, t.z = 10

for z= 30 :      t.x = 6, t.y = 6, t.z = 30 

why these strange outputs ??

Compiler allocate memory for largest union member. Memory for z will be allocated in this case. Since last assignment make z to have value 1 , only this value will be there in memory overriding the previous values. So, the last 3 bits stored in allocated memory is 001 . Accessing other 3 bit members will give result 1 .

For z equals to 2 , 10 , and 30 , last 3 bits are 010 , 010 and 110 respectively which are equal to 2 , 2 and 6 respectively in decimal.

It's a union, that's the way unions work. All of the member variables (x,y,z) are at the same address in memory, so if you change one, you change them all. Technically you should only read the last one that you wrote. Writing to z and then reading from x or y is unspecified behavior.

From the C-11 draft specification §6.2.6.1

When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.


In response to the edit:
The lower three bits of 10 decimal are 010 binary which is 2 decimal.
The lower three bits of 30 decimal are 110 binary which is 6 decimal.

In Union, we can use one member at a time. So at last you assign the value as 1.Refer here.

Union will take the memory which having the highest size in that member. So from that memory all the members have to work in that. At last z will access the memory then make the value as one.

All the members will use the same memory so first two members got the value as one.

You can verify like this. Make a printf after assigning every value.

t.x=5;
printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);
t.y=4
printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);
t.z=1;
printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);

Nothing wrong in it.

Last 3 bits of z are shared with x and y.

for z= 30 tx = 6, ty = 6, tz = 30

z= 0x1E = 00011110.

tx = 110 = 6

ty = 110 = 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM