Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Union:-

Union is a user-defined datatype. All the members of union share same memory
location. Size of union is decided by the size of largest member of union. If you want
to use same memory location for two or more members, union is the best for that.

Unions are similar to structures. Union variables are created in same manner as
structure variables. The keyword “union” is used to define unions in C++ language.

Here is the syntax of unions in C++ language,

union union_name {

member definition;

} union_variables;

Here,

union_name − Any name given to the union.

member definition − Set of member variables.

union_variable − This is the object of union.

For example:

Union DMC

Int RNO;

Float percentage;

Char pass;

} Result;
Difference between structure and union:-
Union and structure are almost same but there is a difference. In structure different
variables are stored at different locations in memory, while in union ; different
variables are stored at the same space in memory.

accessing of union member in C++


As members of the union, we access the dot operator as a structure with the
union-variable.

Here is the syntax, to access union member

union_name.member_name;

Example of union in C++


#include<iostream.h>

#include <conio.h>

union book{

int sr;

char name[20];

float price;

};

int main()

book vr;

cout<<"Enter Serial No.: ";

cin>>vr.sr;
cout<<"Enter Book Name : ";

gets(vr.name);

cout<<"Enter Book Price: ";

cin>>vr.price;

cout<<"Serial No.: "<<vr.sr;

cout<<"\nBook Name : "<<vr.name;

cout<<"\nBook Price: "<<vr.price;

return 0;

OUTPUT
Serial No.: 101

Book Name : Science

Book Price: 350.5

Record
A record is a data structure for storing a fixed number of elements. It is similar to a
structure in C++ language. At the time of compilation, its expressions are translated
to tuple expressions.

How to create a record?

The keyword ‘record’ is used to create records specified with record name and its
fields. Its syntax is as follows −

record(recodname, {field1, field2, . . fieldn})

The syntax to insert values into the record is −

#recordname {fieldName1 = value1, fieldName2 = value2 .. fieldNamen = valuen}

You might also like