Basic programming of Union

C Programming Language Union in C Language (Article) Union in C Language (Program)

27459

Program:

#include<stdio.h>
#include<string.h>
 
union student 
{
            char name[20];
            char subject[20];
            float percentage;
};
 
int main() 
{
    union student record1;
    union student record2;
 
    // assigning values to record1 union variable
       strcpy(record1.name, "Raju");
       strcpy(record1.subject, "Maths");
       record1.percentage = 86.50;
 
       printf("Union record1 values example\n");
       printf(" Name       : %s \n", record1.name);
       printf(" Subject    : %s \n", record1.subject);
       printf(" Percentage : %f \n\n", record1.percentage);
 
    // assigning values to record2 union variable
       printf("Union record2 values example\n");
       strcpy(record2.name, "Mani");
       printf(" Name       : %s \n", record2.name);
 
       strcpy(record2.subject, "Physics");
       printf(" Subject    : %s \n", record2.subject);
 
       record2.percentage = 99.50;
       printf(" Percentage : %f \n", record2.percentage);
       return 0;
}

Output:

 Union record1 values example
 Name       :
 Subject    :
 Percentage : 86.500000

Union record2 values example
 Name       : Mani
 Subject    : Physics
 Percentage : 99.500000
Press any key to continue . . .

Explanation:

A union is a special data type available in C that allows 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 multiple-purpose.

Unions are quite similar to structures in C. Like structures, unions are also derived types.

union car
{
  char name[50];
  int price;
};

Defining a union is as easy as replacing the keyword struct with the keyword union.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.