Type union

How to use type union in C/C++.

Definition

We can define a union as a C data type with some magic inside. If you already know structs this is as simple as a struct
but in this case you can only use a member at the same time. Using other words, you can only give a value to one of its members at
the same time.

Usage

Assuming the following definition:

1
2
3
4
5
union Data {
int i;
float f;
char str[20];
};

We can declare a new variable as follow:

1
union Data data;

We can give values as follow:

1
2
3
data.i = 10;
strcpy( data.str, "C Programming");
data.f = 220.5;

But, this is not a struct, so the above code keeps the value of data.f because is the last assigned member. Keep in mind that we can give value to one
of its members at the same time. If we print the above code we can see garbage on data.i and data.str as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
strcpy( data.str, "C Programming");
data.f = 220.5;

printf( "data.i : %d\n", data.i);
printf( "data.str : %s\n", data.str);
printf( "data.f : %f\n", data.f);

return 0;
}

The above code will show something like this:

1
2
3
4
5
$ gcc -o main main.c
$ ./main
data.i : 1130135552
data.str :
data.f : 220.500000

As we can see, the value for data.i is corrupted, and the value for data.str is corrupted too. The properly way to print and/or use the values would be as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

return 0;
}

Now, the values are used as expected so we can see the right value:

1
2
3
4
5
$ gcc -o main main.c
$ ./main
data.i : 10
data.str : C Programming
data.f : 220.500000

We can see that is an efficient way to have a dynamic struct without pollute the memory, so if you are clever using it, you can win efficiency!

References