Union in C/C++

Union in C/C++

A union is a data type available in C/C++ that allows to store different data types. Every element of a union is called a member. All the members share the same memory location. ‘union‘ keyword is used to define a union.
Syntax-

union abc
{
    ...;
    ...;
    ...;
};

Declaration of union members has 2 methods :

union abc{
...
...
};
int main()
{
union abc x;
...
...
}

or

union abc{
...
...
}x;

Union members cannot be initialized with declaration. Firstly they can be taken as input and then accessed as structure members. So to access any member of a structure, we use the member access operator/ dot operator (.). Secondly you can assign values to each member separately. However, as the union members share memory location the values are overwritten. So if you assign a value to the first member make sure you print or use it wherever needed before assigning the next member value. You will see how it works in the program below.

1. Program in C :

#include<stdio.h>
union student {
  char name[20];
  int age;
  float marks;
}x;

int main() {
  printf(" Enter name: ");
  scanf("%s", & x.name);
  system("cls");
  printf("\n Name: %s\n", x.name);
  x.age = 22;
  printf("\n Age: %d\n", x.age);
  x.marks = 78.90;
  printf("\n Marks: %f", x.marks);
  return 0;
}

2. Program in C++ :

#include<iostream>
using namespace std;
union student {
  char name[20];
  int age;
  float marks;
}x;

int main() {
  cout << " Enter name: ";
  cin >> x.name;
  system("cls");
  cout << "\n Name: " << x.name << endl;
  x.age = 22;
  cout << "\n Age: " << x.age << endl;
  x.marks = 78.90;
  cout << "\n Marks: " << x.marks;
  return 0;
}

3. Output-

union in cpp

4. Parts of program-

1. #include is a pre-processor directive. It is used to include header files.
2. stdio/iostream is header file which has certain commands that c/c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. int, char, float are data types.
5. main() is main function that indicates the compiler that the user written programs starts from here.
6. printf/cout is the keyword use to print a message.
7. scanf/cin is the keyword use to store values in variables.
8. return statement is use to return a value. If any error occurs the program will return 0.

Conclusion-

So this was the concept of Union in C/C++. We hope it was clear to you. If you find it useful then do share it with your programming buddies and friends. Also if you have any doubt regarding any post do tell us in the comment section.

For daily updates do follow us on Instagram. Visit again!

ErrorFreeProgram.

1 COMMENT

Leave a Reply

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