unions in C

Previous
Next

Unions

  • union is a keyword.
  • Unions are used to create user defined data types.
  • Unions working like structure.

Syntax of structure and union :

struct identity
{
	datatype ele-1;
	...
	datatype ele-n;	
};

union identity
{
	datatype ele-1;
	...
	datatype ele-n;	
};

Note: The only difference between structure and union is, structure allocates individual memory locations to all elements where as union allocates common memory to all elements.

#include<stdio.h>
union Test
{
	char c;
	short s;
	float f;
};
int main()
{
	union Test var;
	printf("size of union is : %d \n", sizeof(union Test));
	printf("size of union is : %d \n", sizeof(var));
	return 0;
}
  • Unions were used in early days when memory is at premium.
  • We can define multiple elements into a single union definition but we can use only one element at a time.
  • We access the elements of union using dot(.) operator.
#include<stdio.h>
union Test
{
	int a, b;
};
int main()
{
	union Test var;
	var.a = 10;
	printf("b value : %d \n", var.b);
	
	var.b = 20;
	printf("a value : %d \n", var.a);
	return 0;
}
#include<stdio.h>
union Test
{
	char ch[2];
	short x;
};
int main()
{
	union Test var;
	var.ch[0] = 2;
	var.ch[1] = 3;
	printf("x value : %d \n", var.x);
	return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form