Thursday, March 31, 2016

Difference between Structures and Unions

Structure and union both are user defined data types. The main difference between structure and union is that union uses same memory location for all the member variables hence the size of the union is the size of the largest member variable but structure uses different memory location for all the members. Let’s take an example:
union my_union
{ int my_int;
char my_char2;
char my_char1; } my_union;
int my_int;
struct my_struct { char my_char1;
} my_struct;
char my_char2;
Now if we execute sizeof function over my_struct and my_union then we will see that the output as 4 for union and 6 for structure. As for structure it is simple 4 for integer and 2 for 2 character variables but if for union it happens because of the union’s property of sharing memory location to all members. Union allocates memory equal to the size of the member variable which takes largest in the memory. Here since integer takes 4 bytes and character takes 1 byte each that’s why it takes 4 bytes of memory hence it outputs 4.

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;
}

Tuesday, March 29, 2016

Unions in c programming with example

Union is another user defined data type in C. This is very similar to the structure but there is slight difference between them.
union my_union
{
int var1;
char ch1;
char ch2;
char ch3;
char ch3;
} union1;

union1.var1 = 220;
union1.ch1 = ‘A’;
printf(“value %d”,union1.var1);

Unions in C

To define union, you have to use keyword union. Other things in syntax for union are similar to the structure. Example of declaration and access of union is given below:
union my_union
{
char my_char;
int my_int;
float my_float;
} my_union;