How is union different from structure? Do other languages ​​have similar constructs?

Possible duplicate:
Difference between structure and union in C

I see this code to combine in C:

    union time
    {
      long simpleDate;
      double perciseDate;
    } mytime;

What is the difference between union and structure in C? Where would you use the union, what are its advantages? Is there a similar construction in Java, C ++ and / or Python?

+3
source share
7 answers

So, in your example, when I set aside time:

int main()
{
    time t;
}

The compiler can interpret the memory in & t as if it were long:

t.simpleDate;

or as if its double:

t.perciseDate;

So, if the original hex memory in t looks like

0x12345678;

"" , , . , , , . , 2- , . , .

.

( , , sizeof (long) 32 , sizeof (double) 64 )

, "" (, char) "". , , :

struct Msg
{
   int msgType;
   double Val1;
   double Val2;
}; // assuming packing on 32-bit boundary

union
{
   Msg msg;
   unsigned char msgAsBinary[20];
};

, .

+11

, , .

, - "" , . , , , . , C , , , , ... , :

union {
 int integer;
 float real;
} convert;

convert.real = 3.14;
printf("The float %f interpreted as an integer is %08x", convert.real, convert.integer);

, , , :

typedef enum { INTEGER = 0, REAL, BOOLEAN, STRING } ValueType;

typedef struct {
  ValueType type;
  union {
  int integer;
  float real;
  char boolean;
  char *string;
  } x;
} Value;

, , Value. :

void value_set_integer(Value *value, int x)
{
  value->type = INTEGER;
  value->x.integer = x;
}

, . , , print a Value type :

void value_print(const Value *value)
{
  switch(value->type)
  {
  case INTEGER:
    printf("%d\n", value->x.integer);
    break;
  case REAL:
    printf("%g\n", value->x.real);
    break;
  /* ... and so on ... */
  }
}

Java . ++, - C, . "" C, . ++ (x), .

+14

(, ) .

, , - uint32.

union {
  uint32 int;
  char bytes[4];
} uint_bytes;

, () .

.

+2

- "" . , ; . "" (.. ) undefined; .

"union" ++ (++ C), ++ ( , POD, .. , ). ++, , Boost.Variant.

, , . Java Object, Object * ; , , .

Python , . , ; duck typing - , , /, .

+2

, ( ) . , , .

++ . Java . - Python , C, , . , Python - -, , , C.

+1

, , - . . .

, () / . .

+1

, , . .

+1

Source: https://habr.com/ru/post/1723003/


All Articles