union union_tag
{
datatype member1;
datatype member2;
.
.
.
} var;
union Data
{
int i;
float f;
char str[20];
} data;
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main()
{
union Data data;
printf("Memory size occupied by data : %d", sizeof(data)); // 20
}
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
Output ↓
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Now we will take an example where we will use one variable at a time. Which is the main purpose of having unions - ↓
#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);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
data.i : 10
data.f : 220.500000
data.str : C Programming
For example consider the following union ↓
union student
{
char name[20];
int rollNo;
float fees;
}
Consider the following declaration without the use of bit fields.
#include <stdio.h>
struct order
{
unsigned int isAvailable;
unsigned int isTshirt;
};
int main()
{
printf("Size of order is %lu bytes\n", sizeof(struct order));
struct order hoodie= {1, 0};
printf("The order is %s and it is %s",(hoodie.isAvailable)?"available":"not available", (hoodie.isTshirt)?"T-shirt":"not T-shirt");
return 0;
}
Output ↓
Size of order is 8 bytes
The order is available and it is not T-shirt
// syntax
struct
{
data_type member_name: width_of_bit_field;
};
Now we will see, 'order' representation with bit-fields ↓
#include <stdio.h>
#pragma pack(1)
// space opmitized representation of 'order'
struct order
{
// isAvailable can store either 0 or 1, so 1 bits are sufficient
unsigned int isAvailable : 1;
// isTshirt can store either 0 or 1, so 1 bits are sufficient
unsigned int isTshirt : 1;
};
int main()
{
printf("Size of order is %lu byte\n", sizeof(struct order)); // 1
struct order hoodie= {1, 0};
printf("The order is %s and it is %s",(hoodie.isAvailable)?"available":"not available", (hoodie.isTshirt)?"T-shirt":"not T-shirt");
return 0;
}
Output ↓
Size of order is 1 byte
The order is available and it is not T-shirt