Wednesday, March 30, 2016

Usage of Unions

The main characteristic of union is that it lets you to use same memory location for different data type. In real life C programming, you may encounter a situation where you need to store a value of say 4 byte but at different time according to situation you need to know the value of 1st byte or 3rd byte or may be 4th byte contained value. Yes there is bitwise operators to do that but if you define a union like given above, you can access any byte of value at any time without any logical or arithmetic operation.
#include<stdio.h>
int main() {
char my_char;
union my_union {
} my_union;
int my_int; float my_float;
printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float );
my_union.my_char = 'A'; my_union.my_int = 57;
printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float );
my_union.my_float = 101.357; printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float ); return 0;
}

No comments: