position: fixed; top: auto !important; margin-left: 112px;

Union in C

The only difference between Structure and Union is structure allocates memory for every type whereas union allocates single memory for all the variables.

Union in C is a user-defined data type which allows you to store data elements of a different kind just like structures. Unions are almost the same as structures.

Difference between Structure and Union

The difference between Structure and Union in C is as follows:

 Structures                                         Unions 
     |                                                 |   
     V                                                 V
 struct Student                                    union Student
 {                                                 {
 char name[20];  // 1 byte                           char name[20];       
 int   age;      // 4 bytes                          int   age;         // 4 bytes
 } ;                                               } ;
   
------------------------------------------------------------------------------------------------------------------
Memory Size in Structures = 5 bytes.      Memory in Union = 4 bytes. Largest among char & int is int.

Unions create a single memory location and the size of that location depends on the highest size of the type described inside the union.

Here, char is of 1 byte & int is of 4 bytes.

Which one is greater? int.

So Memory Size of the union, in this case, will be 4 bytes. Whereas, In Structures, memory size will be the sum of all the types described inside structures i.e 5 bytes in our case.

How To Define Union?

The following example shows how to define union:

Syntax :-

union [union Name]
 {
  datatype variable;
  datatype variable;
  ...
  datatype variable;
 } [one or more union variables];

Example Explained

"union Name" is an "Optional" Name which is used to define union.

"datatype variable" is simply declaring a normal variable int a; float per;

"[one or more union variables]" is an "Optional" Name which is used to define one or more union variables.


Example :-

union Student
{
 char name[20]; 
 int   age;
} student; 

How to Access Union Members?

Dot Operator (.) is used to access any union member.

Following example clears the concept :-

#include <stdio.h>
#include <string.h>
union Students
{
    char name[20];
    int   age;
};

int main( )
{
    union Students firstStudent;        /* Declare firstStudent of type Students */
    
    /* firstStudent specification */
    strcpy(firstStudent.name , "Jazzy");
    firstStudent.age = 23;
    
   /* print firstStudent info */
    printf("First Student Name: %s\n", firstStudent.name);
    printf("First Student age: %d\n", firstStudent.age);
    
    return 0;
}

Output:-

First Student Name: Corrupted Value Dsfsmfbsmf smf smf 
First Student age: 23

Unexpected Output Right? First Student name should be Jazzy. Age = 23. But remember unions always create a single memory location consider it like a box containing Value. So we first initialized a name = Jazzy first. Then that single memory box contains Jazzy. Then we initialized age = 23. Then that single memory box contains 23 . Name value is gone now. Union variables are used one at a time. That's why First Student name value is corrupted here.

So to achieve desired output:

#include <stdio.h>
#include <string.h>
union Students
{
    char name[20];
    int   age;
};

int main( )
{
    union Students firstStudent;        /* Declare firstStudent of type Students */
    
    /* firstStudent name */
    strcpy(firstStudent.name , "Jazzy");
    printf("First Student Name : %s\n", firstStudent.name);

   /* print firstStudent info */
    firstStudent.age = 23;
    printf("First Student age : %d\n", firstStudent.age);
    
    return 0;
}

Output:-

First Student Name: Jazzy
First Student age: 23

Unions are useful when you want to use a single memory location for multiple tasks.


Solve the Quiz of Article

1) What do you think Size of union is size of the longest element in the union?
Yes
No

2) What do you think elements of union are always accessed using & operator?
Yes
No


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.