Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Union

Unions are conceptually similar to structures. The syntax to declare/define a union is


also similar to that of a structure. The only differences are in terms of storage.
In structure each member has its own storage location, whereas all members
of union uses a single shared memory location which is equal to the size of its largest
data member.

This implies that although a union may contain many members of different types, it
cannot handle all the members at the same time. A union is declared using
the union keyword.

Syntax of Declaring Union

union [name of union]

type member1;

type member2;

type member3;

};

Union is declared using the "union" keyword and name of union. Number 1, number
2, number 3 are individual members of union. The body part is terminated with a
semicolon (;).

1
union item

int m;

float x;

char c;

}It1;

This declares a variable It1 of type union item. This union contains three members
each with a different data type. However only one of them can be used at a time.
This is due to the fact that only one location is allocated for all the union variables,
irrespective of their size. The compiler allocates the storage that is large enough to
hold the largest variable type in the union.

In the union declared above the member x requires 4 bytes which is largest amongst
the members for a 16-bit machine. Other members of union will share the same
memory address.

Accessing a Union Member in C

Syntax for accessing any union member is similar to accessing structure members,

union test

int a;

float b;

char c;

}t;

t.a; //to access members of union t

t.b;

t.c;

Example of Union

#include <stdio.h>

2
union item

int x;

float y;

char ch;

};

int main( )

union item it;

it.x = 12;

it.y = 20.2;

it.ch = 'a';

printf("%d\n", it.x);

printf("%f\n", it.y);

printf("%c\n", it.ch);

return 0;

Output:

1101109601

20.199892

In the above program, you can see that the values of x and y gets corrupted. Only
variable ch prints the expected result. It is because, in union, the memory location is
shared among all member data types.

3
Structure Vs. Union

Structure Union

You can use a struct keyword to define a You can use a union keyword to define a union.
structure.

Every member within structure is assigned a In union, a memory location is shared by all the
unique memory location. data members.

Changing the value of one data member will not Changing the value of one data member will
affect other data members in structure. change the value of other data members in union.

It enables you to initialize several members at It enables you to initialize only the first member
once. of union.

The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.

It is mainly used for storing various data types. It is mainly used for storing one of the many data
types that are available.

It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.

You can retrieve any member at a time. You can access one member at a time in the
union.

It supports flexible array. It does not support a flexible array.

Advantages of union

Here, are pros/benefits for using union:

 It occupies less memory compared to structure.

 When you use union, only the last variable can be directly accessed.

 Union is used when you have to use the same memory location for two or more
data members.

 It enables you to hold data of only one data member.

 Its allocated space is equal to maximum size of the data member.

Disadvantages of union

Here, are cons/drawbacks for using union:

4
 You can use only one union member at a time.

 All the union variables cannot be initialized or used with varying values at a
time.

 Union assigns one common storage space for all its members.

NOTE:

Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C


programming language.

 For the structures in C programming language from C99 standard onwards, we


can declare an array without a dimension and whose size is flexible in nature.

 Such an array inside the structure should preferably be declared as the last
member of structure and its size is variable(can be changed be at runtime).

 The structure must contain at least one more named member in addition to the
flexible array member.

Size of struct in :
We know is that size of a struct is the sum of all the data members.

Like for the following struct,

struct A{

int a;

int* b;

char c;

char *d;

};

Size of the struct should be sum of all the data member, which is: Size of int a+
size of int* b +size of char c+ size of char* d

Now considering the 64-bit system,

Size of int is 4 Bytes

Size of character is 1 Byte

Size of any pointer type is 8 Bytes

5
(Pointer size doesn't depend on what kind of data type they are pointing too)

So the size of the struct should be: (4+8+1+8)=21 Bytes

Structure padding in C:

When you create the structure or union then compiler inserts some extra bytes
between the members of structure or union for the alignment. These extra unused
bytes are called padding bytes and this technique is called structure padding in C.

 Padding increases the performance of the processor at the penalty of memory.


In structure or union data members aligned as per the size of the highest bytes
member to prevent the penalty of performance.

 Because of this structure padding concept in C, size of the structure is always


not same as what we think.

Example:

#include <stdio.h>

struct A

int a;

int* b;

char c;

char* d;

};

int main( )

struct A a;

printf("Size of struct A: %lu\n", sizeof(struct A));

printf("Size of object a: %lu\n", sizeof(a));

return 0;

6
Output:

Size of struct A: 32

Size of object a: 32

The
he compiler adds padding and tries to align the data members. So for the above
structure, the data alignment looks like below.
below

Above is the alignment of the structure A, and that's why the size of the struct is 32
Bytes. Also, the object a of type struct A is 32 Bytes.

How compiler adds padding?

It aligns till the boundary of maximum memory allocated. Here we find that max
memory allocated is 8 Bytes, thus all the data members acquire 8 Bytes and the ttotal
size is 32 Bytes.

How to avoid Structure Padding in C?

If you want you can avoid the structure padding in C using the pragma pack (#pragma
pack(1) ) or attribute ( __attribute__((__packed__)) ).

#include <stdio.h>

#pragma pack(push, 1)

struct A

int a;

int* b;

char c;

char* d;

};

7
#pragma pack(pop)

int main()

struct A a;

printf("Size of struct A: %lu\n", sizeof(struct A));

printf("Size of object a: %lu\n", sizeof(a));

return 0;

Output:

Size of struct A: 21
Size of object a: 21

Note:
We can also change the alignment of structure, union or class using the “pack”
pragma directive, but sometimes it becomes a crucial reason for the compatibility
issues in your program. So it’s better always use the default packing of the compiler.

You might also like