***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Posts

    Friday, November 27, 2020

    Union

    Like structure, Union in c language is a user-defined data type that is used to store the different type of elements.

    At once, only one member of the union can occupy the memory. In other words, the size of the union in any instance is equal to the size of its largest element.

    Unions provide an efficient way of using the same memory location for multiple-purpose.

    Defining union

    The union keyword is used to define the union. Let's see the syntax to define union in c.

    union  union_name  

    { 

        data_type member1; 

        data_type member2; 

        . 

        . 

        data_type memeberN; 

    }; 

     

    The example to define union for an employee in c.

    union employee 

    {   int id; 

        char name[50]; 

        float salary; 

    };

     Allocation of memory to a structure and a union example:


    Declaring union variable

     A variable for the union has to be declared to access the member of the union easily.

    There are two ways to declare union variable:

     

    1. By union keyword within main() function
    2. By declaring a variable at the time of defining the union.

     First Method:

     union employee 

        int id; 

        char name[50]; 

        float salary; 

    };

    After defining structure write below code inside the main() function.

    union employee e1, e2; 

    The variables e1 and e2 can be used to access the values stored in the union.

    Second Method:

    union employee 

    {  

        int id; 

        char name[50]; 

        float salary; 

    }e1,e2; 

     

    If number of variables is not fixed, use the first method. It provides the flexibility to declare the union variable as many times as required

    Accessing members of the Union

    There are two ways to access union members:

    1. By . (member or dot operator)
    2. By -> (structure pointer operator)

    A pointer can be created to a union. If a pointer to union is created, members are accessed using arrow ( -> ) operator.

    Example:

    #include <stdio.h> 

    #include <string.h> 

    union employee   

    {   int id;   

        char name[50];   

    }e1;  //declaring e1 variable for union 

    int main( ) 

       //store first employee information 

       e1.id=101; 

       strcpy(e1.name, "Ashraf");//copying string into char array 

       //printing first employee information 

       printf( "employee 1 id : %d\n", e1.id); 

       printf( "employee 1 name : %s\n", e1.name); 

       return 0; 

    }


    No comments:

    Post a Comment

    Top