How to use Union in C language

馋奶兔 提交于 2019-12-05 12:12:53

Assuming you use

printf("%d", x.j); 

You will see the same value you assigned to x.i, since both variables occupy the same area of memory. It would not be typical to make both variables of the same type like you have done. More typically you would do this so that you can view the same data but as different data types.

Imagine for example that you wanted to treat a double both as a double and at times directly access the bits (1s and 0s) that represent the double, you would do that with the following union.

union DoubleData
{
    double d;
    char b[8];
} x;

Now you can assign/access the double directly through the d member or manipulate the same value through the 8 bytes that represent the double in memory.

Using your recent update to the question,

union student 
{       
  int i;
  float j;    
}x;

Lets make an assumption about your platform, an int is 4 bytes and a float is 4 bytes. In this case when you access x.j you will manipulate and treat the 4 bytes as a double, when you access x.i you will manipulate and treat the 4 bytes as an integer.

So both variables are overlaid in the same memory area, but what will differ is how you interpret the bit pattern in that memory area. Keep in mind that any 4 byte bit pattern is a valid int, BUT not any 4 byte bit pattern is a valid float.

Lets make another assumption about your platform, and int is 2 bytes and a float is 4 bytes. In this case when you access x.i you will only be manipulating half of the bit pattern that is overlaid by the float, because x.i in this case would only partially overlay x.j since x.j covers more bytes.

Both i and j will be sharing the same memory so whatever you assign to one will be available in other member as well.

x.i  = 1;
// x.j = 1

This is "undefined behaviour".

You may not write to i and then read from j. You can only "use" one of the elements at a time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!