开发者

How to use Union in C language

开发者 https://www.devze.com 2023-03-01 14:02 出处:网络
I have a question about union in C Language. The variables declared in a union will share the same memory, ok, I understand.

I have a question about union in C Language. The variables declared in a union will share the same memory, ok, I understand. for example,

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

how c开发者_StackOverflow中文版ould we access the i and j? if we have: x.i = 1; and then we printf("%d",j); what will happen? compiler error? Ok then what about the following case:

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

if we assign x.i = 2; what is the value of x.j?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号