UNION in C

  • The memory space required to store one variable of union is equal to the memory space required by the largest element in the union
  • It is a collection of multiple data elements that can be of different data types. But, only one of these data item can be stored in the union variable
  • It is a variable that may hold objects of different types and sizes, with the compiler keeping track of size and alignment requirements
  • Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program
  • They are analogous to variant records in pascal
  • As an example which might find in a compiler symbol table manager, suppose that a constant may be an int, float, or a character pointer
  • The value of particular constant must be stored in a variable of the proper type, yet it is most convenient for table management if the value occupies the same amount of storage and is stored in the same place regardless of its type
  • This is the purpose of a union-a single variable that can legitimately hold any of one of several types
Syntax of Union
union union_name
{
data_type variable_name;
data_type variable_name;
-
-
}; 
union info
{
int ival;
float fval;
char *sval;
}u;
  • The variable u will be large enough to hold the largest of three types; the specific size is implementation-dependent
  • Any of these types may be assigned to u and then used in an expression, so long as the usage is consistent: the type retrieved must be the type most recently stored
  • It is the programmer’s responsibility to keep track of which type is currently stored in the union;
  • The result is implementation-dependent if something is stored as one type and extracted as another

Display the program to store the information of a person as his name and id by using union ask the user for information choice.

#include<stdio.h>
#include<conio.h>
union person
{
char name[20];
int id;
}p;
void main()
{
int choice;
printf("enter your information \n 1.name:\n2.id  enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:scanf("%s",p.name);
break;
case 2:scanf("%d",&p.id);
break;
default:
printf("Invalid choice");
break;
}
if(choice==1)
{
printf("name=%s",p.name);
}
else{
if(choice==2)
{
printf("id=%d",p.id);
}
}
getch();
}

The union may occur within structures and arrays, and vice versa.The notation for accessing a member of a union in a structure(or vice versa) is identical to that for nested structures

For example:

struct
{
char *name;
int flags;
int utype;
union
{
int ival;
float fval;
char *sval;
}u;
}symtab[NSYM];
Translate »