Learning C #13: Getting to Know the Union Data Type in C

 


Understanding union data types in C

After learning about Struct , next we will get acquainted with the Union data type.

What is union?

Why do we need a union?

..and how to use union?

Let's learn!

What is Union?

Union is a data type that contains a set of variables wrapped together and has the same memory address .

This data type was added in the C111

Why do we need a union?

To answer this, we will use a case study.

For example, we are going to make a game, then want to save data on the weapons owned by the player.

Let's just say the player has two weapons, namely: a gun and a knife.

Then we can create a struct like this:

typedef struct {
	char *nama;
	int jumlah_peluru;
	int ketajaman;
} Senjata;

Pay attention to the variables jumlah_peluruand ketajaman. This variable is required for each type of weapon.

Guns require jumlah_peluruand knives require ketajaman.

If the player only has a gun, that means the variable ketajamanwill be in vain. Vice versa.

So, so that it's not wasted, we have to store the variable jumlah_peluruin ketajamanone memory address.

We can do this with a union like this:

typedef struct {
	char *nama;
	union {
		int jumlah_peluru;
		int ketajaman;
	}
} Senjata;

This way, variables jumlah_peluruand ketajamanwill use the same memory address. This will certainly be more efficient.

So why do we need union?

Union we need when we want to use one memory address for two or more variables.

How to Create a Union

We can create a union with keywords unionfollowed by the name of the union.

After that we use curly braces to define members and their data types.

define union

Example:

union Product {
  char *name;
  unsigned int price;
  unsigned int stock;
  float weight;
};

Then how to use it:

union Product p;

If we use typedef, we don't need to write union every time we use it.

Example:

// mendefinisikan union
typedef union {
  char *name;
  int price;
} Product;

//  menggunakan union
Product p;

Apart from that, Unions can also be created without a name.

Example:

union 
{
  float x;
  float y;
};

We can also store this unnamed union in a struct.

Example:

struct Buku 
{
  char *title ;
  bool is_digital;
  union 
  {
  	char *format;
    float weight;
  };
};

In the struct Bukuthere is uniona nameless struct containing variables formatand weight. These two variables will use the same memory address and can be directly accessed from the struct Buku.

Example:

// membuat variabel struct
Buku belajar_c;

// mengakses union di dalam struct
belajar_c.format = "PDF";

To understand better, let's try practicing.

Practice: Using Union

After knowing how to define or create a union, it's time to try using it.

Create a new program with the name contoh_union.c, then fill in the code like this:

#include <stdio.h>

enum notif_type {EMAIL, SMS};

typedef struct {
    char *title;
    char *message;
    enum notif_type type;
    union {
        char *phone_number;
        char *email_address;
    }
} Notification;

int main(){
    Notification sms;
    Notification email;

    sms.type = SMS;
    sms.title = "Greeting";
    sms.message = "Halo selamat datang";
    sms.phone_number = "081234567890";

    email.type = EMAIL;
    email.title = "Welcome";
    email.message = "Selamat datang di aplikasi";
    email.email_address = "mail@example.com";

    printf("## 🔔 NOTIFICATION SMS ##\n");
    printf("to: %s\n", sms.phone_number);
    printf("message: %s\n", sms.message);

    printf("## ✉ NOTIFICATION EMAIL ##\n");
    printf("subject: %s\n", email.title);
    printf("to: %s\n", email.email_address);
    printf("message: %s\n", email.message);

    return 0;
}

After that, try compiling and running it.

So the result is:

union example

In this program, we create a notification system with two different types of notifications. There are notifications in the form of email and SMS.

Thanks to union we can determine the destination of sending notifications with different types, namely can phone_numberand email_address.

Difference between Union and Struct

Union is actually the same as the Struct data type. However, they differ in their memory allocation methods.

The struct allocates memory for each member at a different memory address.

Meanwhile, Union allocates memory at one memory address with the size taken from the size of the largest member.

Examples:

struct Player {
  char *name; // address: aabbccdd
  unsigned int level; // address: aaffeedd
}

union Enemy {
  char *name; // 11ffdd22
  unsigned int hp; // 11ffdd22
}

Each member of the struct Playerwill use a different memory address. Meanwhile, union Enemyonly uses one memory address.

To make it clearer, let's try practice.

Practice: Struct vs Union

Create a new program with the name union_vs_struct.c, then fill it with the following code:

#include <stdio.h>

int main(){

    struct Player {
        char *name;
        unsigned int level;
    };

    union Enemy {
        char *name;
        unsigned int hp;
    };

    struct Player player1;
    player1.name = "Petani Kode";
    player1.level = 1;

    printf("Player  : %d  (address = %x)\n", sizeof(player1), &player1);
    printf(" - name : %d  (address = %x)\n", sizeof(player1.name), &player1.name);
    printf(" - level: %d  (address = %x)\n", sizeof(player1.level), &player1.level);


    union Enemy zombie;
    zombie.name = "Zombie 1";
    zombie.hp = 100;

    printf("Enemy   : %d  (address = %x)\n", sizeof(zombie), &zombie);
    printf(" - name : %d  (address = %x)\n", sizeof(zombie.name), &zombie.name);
    printf(" - Hp   : %d  (address = %x)\n", sizeof(zombie.hp), &zombie.hp);

    return 0;
}

After that, try compiling and running it.

So the result is:

union example

The memory size of the union Enemyis 8because it takes the size of the largest member, namely the size of name.

The memory address used by each member unionis the same. Unlike structs Playerwhere the addresses are different.

What's next?

We have learned and understood the union type in C. We don't always have to use union.

But..

In certain cases as exemplified above, we are advised to use union.

Next, please learn about string and pointer data types in C.

If there is something you don't understand, please ask in the comments.

Post a Comment

Previous Post Next Post