Unions
is a user-defined data type that enables the storage of different data types in the same memory location. Unlike structures, where each member has its own memory space, members of a union share the same memory space. The size of a union is determined by the size of its largest member. Unions are useful when you need to represent a single memory location that can hold values of different types interchangeably.
Syntax of Unions
union
union_name
{
data_type
member1
;
data_type
member2
;
;
Declaring and using Unions
You can declare variables of a Union type in the same way you declare variables of basic data types.
union
Number
{
int
integerValue
;
float
floatValue
;
;
union
Number
num
;
num.integerValue
= 42;
printf
("Integer Value: %d
",
num.integerValue
);
num.floatValue
= 3.14;
printf
("Float Value: %.2f
",
num.floatValue
);
Size of Union in C
A union in C like a shared storage space where you can keep different types of things, but the size of the storage is determined by the largest thing you want to put in there. It's like having a box that can fit a big toy or several smaller toys. No matter what you put in the box, it won't overflow because everything shares the same space. This helps save memory, making it a smart choice when you want to use one storage for different-sized things without wasting any space.
union
Data
{
int
integerValue
;
char
charValue
;
;
printf
("Size of Data union: %lu bytes
",
sizeof
(
union
Data
));
Example of Unions
#include
<stdio.h>
Copy Code
union
Number
{
int
integerValue
;
float
floatValue
;
;
int
main
() {
union
Number
num
;
num.integerValue
= 42;
printf
("Integer Value: %d
",
num.integerValue
);
num.floatValue
= 3.14;
printf
("Float Value: %.2f
",
num.floatValue
);
return
0;
Output
Integer Value: 42
Float Value: 3.14
In this example,
1. The Number union is defined with two members: integerValue and floatValue.
2. A variable num of type union Number is declared.
3. The integerValue member is assigned the value 42 and then displayed.
4. The floatValue member is assigned the value 3.14, and its value is displayed.
This demonstrates how a union allows you to use the same memory space for different types of data interchangeably. In this case, the union is used to store both an integer and a float at different times.
Diffrence between Structures and Unions