Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 11 February 2014

Unions in C

A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

 Defining a Union

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:
union [union tag]
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables];  
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:
union Data
{
   int i;
   float f;
   char  str[20];
} data;  
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   printf( "Memory size occupied by data : %d\n", sizeof(data));

   return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   data.i = 10;
   data.f = 220.5;
   strcpy( data.str, "C Programming");

   printf( "data.i : %d\n", data.i);
   printf( "data.f : %f\n", data.f);
   printf( "data.str : %s\n", data.str);

   return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   data.i = 10;
   printf( "data.i : %d\n", data.i);
   
   data.f = 220.5;
   printf( "data.f : %f\n", data.f);
   
   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i : 10
data.f : 220.500000
data.str : C Programming


Diffrence between structs and unions:
 


 

 

 

 

 

 

Structure

Union

1.The keyword  struct is used to define a structure
1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of  sizes of its members. The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the  compiler allocates the  memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.




Difference Between Stucture and Union :


Structure Union
i. Access Members     
We can access all the members of structure at anytime. Only one member of union can be accessed at anytime.
ii. Memory Allocation     
Memory is allocated for all variables. Allocates memory for variable which variable require more memory.
iii. Initialization     
All members of structure can be initialized Only the first member of a union can be initialized.
iv. Keyword     
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
v. Syntax     
struct struct_name
{
    structure element 1;
    structure element 2;
 ----------
 ----------
    structure element n;
}struct_var_nm;
union union_name
{
    union element 1;
    union element 2;
 ----------
 ----------
    union element n;
}union_var_nm;
vi. Example     
struct item_mst
{
    int rno;
    char nm[50];
}it;
union item_mst
{
    int rno;
    char nm[50];
}it;

Fig.: Difference between Structure and Union

No comments:

Post a Comment