0% found this document useful (0 votes)
27 views

Union Iin C

A union is a user-defined data type that allows storing different data types in the same memory location. Only one data member can contain a value at any given time. Unions provide a way to interpret the same memory in multiple ways. The size of a union is equal to the size of its largest member. Unions are useful for implementing data structures where the same memory needs to represent different types of nodes.

Uploaded by

qitenicejal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Union Iin C

A union is a user-defined data type that allows storing different data types in the same memory location. Only one data member can contain a value at any given time. Unions provide a way to interpret the same memory in multiple ways. The size of a union is equal to the size of its largest member. Unions are useful for implementing data structures where the same memory needs to represent different types of nodes.

Uploaded by

qitenicejal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Union

Union can be defined as a user-defined data type which is a collection of different


variables of different data types in the same memory location. The union can also be
defined as many members, but only one member can contain a value at a particular
point in time.

Union is a user-defined data type, but unlike structures, they share the same memory
location.

The Union is a user-defined data type in C language that can contain


elements of the different data types just like structure. But unlike structures,
all the members in the C union are stored in the same memory location. Due
to this, only one member can store data at the given instance.

Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as follows:

C Union Declaration

In this part, we only declare the template of the union, i.e., we only declare the
members’ names and data types along with the name of the union. No memory is
allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};
Keep in mind that we have to always end the union declaration with a semi-colon.

Different Ways to Define a Union Variable

We need to define a variable of the union type to start using union members. There
are two methods using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.

Access Union Members

We can access the members of a union by using the ( . ) dot operator just like
structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the nested
unions.
var1.member1.memberA;
Here,
 var1 is a union variable.
 member1 is a member of the union.
 memberA is a member of member1.

Initialization of Union in C

The initialization of a union is the initialization of its members by simply assigning


the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value
at a given instance of time.
Example of Union
C
// C Program to demonstrate how to use union
#include <stdio.h>

// union template or declaration


union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{

// defining a union variable


union un var1;

// initializing the union member


var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}

Output
The value stored in member1 = 15

Size of Union
The size of the union will always be equal to the size of the largest member of the
array. All the less-sized elements can store the data in the same space without any
overflow.

Example 1: C program to find the size of the union

C
// C Program to find the size of the union
#include <stdio.h>

// declaring multiple unions


union test1 {
int x;
int y;
} Test1;

union test2 {
int x;
char y;
} Test2;

union test3 {
int arr[10];
char y;
} Test3;

// driver code
int main()
{
// finding size using sizeof() operator
int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);

printf("Sizeof test1: %d\n", size1);


printf("Sizeof test2: %d\n", size2);
printf("Sizeof test3: %d", size3);
return 0;
}

Output
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40

Difference between C Structure and C Union


The following table lists the key difference between the structure and union in C:

Structure Union

The size of the structure is equal to or greater than The size of the union is the size
the total size of all of its members. of its largest member.

The structure can contain data in multiple Only one member can contain
members at the same time. data at the same time.

It is declared using the union


It is declared using the struct keyword.
keyword.

#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}

In the above code, we have created a pointer variable, i.e., *ptr, that stores the
address of var variable. Now, ptr can access the variable 'a' by using the (->)
operator. Hence the output of the above code would be 90.

FAQs on C Unions
1. What is the size of the given union?

union un {
int a;
int arr[20];
}
Ans: The size of the given union is 20 x 4 bytes = 80 bytes. Even if the array is a
collection of similar data elements, it is considered to be a single entity by the C
compiler.

2. Can we store data in multiple union members at the same time?

No. We can only store data in a single member at the same time. For example in the
following C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.

C
// C program to check if we can store data in multiple union
// members
#include <stdio.h>

// Declaration of union is same as structures


union test {
int x, y;
};

int main()
{
// A union variable t
union test t;

t.x = 2; // t.y also gets value 2


printf("After making x = 2:\n x = %d, y = %d\n\n", t.x,
t.y);

t.y = 10; // t.x is also updated to 10


printf("After making y = 10:\n x = %d, y = %d\n\n", t.x,
t.y);
return 0;
}

Output
After making x = 2:
x = 2, y = 2
After making y = 10:
x = 10, y = 10

3. What are the applications of unions?

Unions can be useful in many situations where we want to use the same memory for
two or more members. For example, suppose we want to implement a binary tree
data structure where each leaf node has a double data value, while each internal node
has pointers to two children, but no data. If we declare this as:

C
struct NODE {
struct NODE* left;
struct NODE* right;
double data;
};

then every node requires 16 bytes, with half the bytes wasted for each type of node.
On the other hand, if we declare a node as the following, then we can save space.

C
struct NODE {
bool is_leaf;
union {
struct {
struct NODE* left;
struct NODE* right;
} internal;
double data;
} info;
};

nitially, they decided to store the records in a structure as shown below:

1. struct store
2. {
3. double price;
4. char *title;
5. char *author;
6. int number_pages;
7. int color;
8. int size;
9. char *design;
10. };

The above structure consists of all the items that store owner wants to store. The
above structure is completely usable but the price is common property in both the
items and the rest of the items are individual. The properties like price, *title, *author,
and number_pages belong to Books while color, size, *design belongs to Shirt.

Let's see how can we access the members of the structure.

1. int main()
2. {
3. struct store book;
4. book.title = "C programming";
5. book.author = "Paulo Cohelo";
6. book.number_pages = 190;
7. book.price = 205;
8. printf("Size is : %ld bytes", sizeof(book));
9. return 0;
10. }

In the above code, we have created a variable of type store. We have assigned the
values to the variables, title, author, number_pages, price but the book variable does
not possess the properties such as size, color, and design. Hence, it's a wastage of
memory. The size of the above structure would be 44 bytes.

We can save lots of space if we use unions.

#include <stdio.h>
struct store
{
double price;
union
{
struct{
char *title;
char *author;
int number_pages;
} book;

struct {
int color;
int size;
char *design;
} shirt;
}item;
};
int main()
{
struct store s;
s.item.book.title = "C programming";
s.item.book.author = "John";
s.item.book.number_pages = 189;
printf("Size is %ld", sizeof(s));
return 0;
}
In the above code, we have created a variable of type store. Since we used the unions
in the above code, so the largest memory occupied by the variable would be
considered for the memory allocation. The output of the above program is 32 bytes.
In the case of structures, we obtained 44 bytes, while in the case of unions, the size
obtained is 44 bytes. Hence, 44 bytes is greater than 32 bytes saving lots of memory
space.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy