1. C Programs
  2. Unions In C

C Program to understand concept of Union

Union

union is a user-defined data type available in C that allows all members 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.

Example

Keyword used to define it is union.

C Program to understand concept of Union

Like here, the union variable Emp has used two datatypes char type and float type. And the members X and Y are stored in a same memory location with memory storage of 4 bytes. Here the size of the union variable is 4 because the size of the union variable will always be the size of its largest element(i.e; the size of float y which is 4 bytes).To understand this more we have, Basic Program to understand the Concept of Union:



#include <stdio.h>
 
void main()
 
{
 
    union number
 
    {
 
        int  n1;
 
        float n2;
 
    };
 
    union number x;
     
    printf("Enter the value of n1: ");
 
    scanf("%d", &x.n1);
 
    printf("Value of n1 = %d", x.n1);
 
    printf("\nEnter the value of n2: ");
 
    scanf("%f", &x.n2);
 
    printf("Value of n2 = %f\n", x.n2);
 
}

Output

Enter the value of n1: 10
Value of n1 = 10
Enter the value of n2: 50
Value of n2 = 50.000000

 

We hope that this program helps you. If you have more better approach to solve the program which can be easily understand , feel free to drop a comment or write to us at admin@wikicoders.org . We will be more than happy to share the program.

 

 

Comments to: C Program to understand concept of Union

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

Login

Welcome to WikiCoders

Join the site and store the save posts for later, share your own articles
Join WikiCoder
Registration is closed.