Proper use of the Union

My understanding of the union is that all its values ​​are distributed at the same memory address, and the memory space is equal to a large member of the union. But I do not understand how we will use them. This is code in which the use of union is preferable according to the C ++ programming language .

enum Type { str, num };

struct Entry {
     char* name;
     Type t;
     char* s;  // use s if t==str
     int i;    // use i if t==num
};

void f(Entry* p)
{
     if (p->t == str)
           cout << p->s;
     // ...
}

After that, Bjarne says:

s , . , , , :   union Value {        char * s;        int i;   }; , , :   struct Entry {        char * ;         t;         v;// v.s, t == str; v.i, t == num   };   void f (Entry * p)   {         (p- > t == str)              cout v.s;        //...   }

- ? , ?

+4
3

, 32- 32- . :

[0-3] name
[4-7] type
[8-11] string
[12-15] integer

16 , type (t ) , , string integer . :

struct Entry {
  char* name;
  Type t;
  union {
    char* s;  // use s if t==str
    int i;    // use i if t==num
  } u;
};

:

[0-3] name
[4-7] type
[8-11] string
[8-11] integer

++ , , "" , , , . " ", "" type.

, 12 16. , . .

+6

union mix_types {
  int l;
  struct {
    short hi;
    short lo;
    } s;
  char c[4];
} mix;

: -

enter image description here

+2

Another way to use unions is to access the same data using different types. An example is the DirectX matrix structure,

typedef struct _D3DMATRIX {
    union {
        struct {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;

        };
        float m[4][4];
    };
} D3DMATRIX;

Now you can do

D3DMATRIX d;
d._11 = 20;
// Now the value of m[0][0] is 20
assert(d._11 == m[0][0]);
0
source

All Articles