Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • union in C

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 354
    Comment on it

    A union is a special data type available in C that allows to store different data types in the same memory location just like structures in C.

    Union uses a single shared memory location which is equal to the size of its largest data member. It provide an efficient way of using the same memory location for multiple-purpose.

    Union is used to store student information, employee information, product information, book information etc.

    Defining a Union

    The union keyword is used to define union. syntax to define union in c is:

    union [union tag] {
       member definition;
       member definition;
       ...
       member definition;
    } [one or more union variables]; 
    

    The following example displays the 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;
        }
    

    Output:- When the above code is compiled and executed, it produces the following result -

     Memory size occupied by data : 20
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: