Union In C Programming  

Unions in c is like structure contain members whose individual data types may differ from one another. However, the members that compose a union all share the same storage area within the computer's memory whereas each member within a structure is assigned its own unique storage area.  Thus unions are used to observe memory.  They are useful for application involving multiple members, where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:           

union item
         
{                 
int m;               
 float p;                 
char c;         
}         
code;
     
This declares a variable code of type union item. The union contains three members each with    a different data type. However, we can use only one of them at a time. This is because if only    one location is allocated for union variable irrespective of size. The compiler allocates a piece    of storage that is large enough to access a union member we can use the same syntax that we    use to access structure members. That is
            
code.m       
 code.p         
code.c
     
are all valid member variables? During accessing we should make sure that we are accessing    the member whose value is currently stored.   
For example, a statement such as
            
code.m=456;           
code.p=456.78;           
printf(“%d”,code.m);     



  More on Structure  

  typedef Keyword      

There is an easier way to define structs or you could "alias" types you create. For example:   
typedef struct
 
{       
char firstName[20];
 char lastName[20];       
char SSN[10];       
float gpa;       
}
 student; 

Now you can use student directly to define variables of student type without using struct keyword. Following is the example:
          
student student_a;   
You can use typedef for non-structs:     
typedef long int *pint32;             
pint32 x, y, z;                 
 x, y and z are all pointers to long ints

Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours