1 of 6

1

12/31/2022

Unions

2 of 6

union

  • A union is a derived data type – like a structure.
  • But, members of a union share the same storage space.
    • union number {

int x;

double y;

};

union number a;

    • If double occupies 8 bytes and int x occupies 4 bytes, the variable a occupies only 8 bytes (not 16 bytes).
    • In the variable a you can store either an int or a double.

2

12/31/2022

3 of 6

union

      • union number {

int x; double y;

} a;

a.x = 5;

printf(“%d”, a.y); /* you will see some garbage on the screen, need not be 5.0 */

      • Language does not provide with automatic type conversion.
      • So, you should somehow remember which member can be accessed.

3

12/31/2022

4 of 6

You should remember which member has the value !

      • enum flag {first, second};

typedef enum flag Flag;

union number {

int x; double y;

};

struct Numb{

Flag f;

union number a;

};

struct Numb n;

n.a.x = 5;

n.f = first;

4

12/31/2022

5 of 6

Intialization

    • In a declaration, a union may be initialized only with a value of the same type as the first union member.
    • union number {

int x; double y;

};

union number a = {10}; /* OK */

union number b = {10, 1.43}; /* error */

5

12/31/2022

6 of 6

Operations with unions

    • Operation that can be performed are same as operations allowed with structures.
      • Assignment to the same typed unions.
      • Taking its address with &
      • Accessing its members.
      • Using sizeof operator to find a union’s size

6

12/31/2022