Accessing inactive union member and undefined behavior?

前端 未结 5 1291
独厮守ぢ
独厮守ぢ 2020-11-21 06:00

I was under the impression that accessing a union member other than the last one set is UB, but I can\'t seem to find a solid reference (other than answers clai

5条回答
  •  感动是毒
    2020-11-21 06:39

    I well explain this with a example.
    assume we have the following union:

    union A{
       int x;
       short y[2];
    };
    

    I well assume that sizeof(int) gives 4, and that sizeof(short) gives 2.
    when you write union A a = {10} that well create a new var of type A in put in it the value 10.

    your memory should look like that: (remember that all of the union members get the same location)

           |                   x                   |
           |        y[0]       |       y[1]        |
           -----------------------------------------
       a-> |0000 0000|0000 0000|0000 0000|0000 1010|
           -----------------------------------------
    

    as you could see, the value of a.x is 10, the value of a.y1 is 10, and the value of a.y[0] is 0.

    now, what well happen if I do this?

    a.y[0] = 37;
    

    our memory will look like this:

           |                   x                   |
           |        y[0]       |       y[1]        |
           -----------------------------------------
       a-> |0000 0000|0010 0101|0000 0000|0000 1010|
           -----------------------------------------
    

    this will turn the value of a.x to 2424842 (in decimal).

    now, if your union has a float, or double, your memory map well be more of a mess, because of the way you store exact numbers. more info you could get in here.

提交回复
热议问题