Union and Enumeration in C++





Union in C++

Union is also used to group a number of different variables together under a common name. Hence, it is similar to structure with a difference in the way the data is stored and retrieved. In structure, each member has its own storage location, whereas all the member of union else the same location.

When a union is declared, compiler automatically allocates a memory location to hold the largest data type of member in the union. Thus, the union is used for saving memory. The concept of union is useful when it is necessary to assign the values to all the member of the union at a time.

The union can be declared using the keyword union as follows:-

 

Union name

{

Data_type member1;

Data_type member 2;

Data_type member n;

} variable_name;

 

Enumeration in C++


It is a method or approach to define user’s own data type. Hence, the enumerated data type is known as user-defined data type. Enum keyword is used to indicate enumerated data type. There permissible values are called member. Then, the variables of this enumerated type can be given any of the values listed in the enum specifier. User can’t give values that weren’t listed in the specifier.

E.g.

//demonstration of enum type

#include<iostream.h>

#include<conio.h>

Void main ()

{

Enum days {sun, mon, tue, wed, thrus, fri, sat};

Days day1, day2;

Day1= sun;

Day2= Mon;

Int diff= day2 – day1;

Cout<<”\n days between=”<<diff;

If (day1 < day2)

{

Cout<<”\n day 1 comes before day 2”;

}

getch ();

}



Related posts:

  1. Structure in C++ Structure in C++ Structure is a collection of simple variables...
  2. Pointer , New and Delete in C++ Pointer A pointer is a variable that contains address of...
  3. Class In C++ Class in c++ Class is a group of similar object....
  4. Predefined Data Types Predefined data types Data can be of many types (e.g....
  5. C++ Cast Explicit type conversion (casts) in c++ or c++ cast It...