Structure and Union in C++

Union :-

It is a user define datatypes which is used to combine items with different types. All the member 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 for two or more members, union is the best for that .  



In Union we use different variables in different function .

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 and C++ languages. 

Structure:-

It is a user-define function datatypes which is used to combine items with same type. Each variable in the structure is known as a member of the structure .Unlike an array ,a structure can contain many different data types (int, string , bool etc).

Syntax of structure :-

struct student

{

id;

int marks;

float per;

};

Syntax of union :-

union student

{

int id;

int marks;

float per;

};

let take an example to write a program to print the student detail using union and structure: (using only turbo c++)

program using with union :

#include <iostream.h>

#include<conio.h>

union student

{

 int id;

int marks;

float per;

};

int main()

{

clrscr();

  union student int ashraf, tahseen, faiyaz;

cin>>ashraf.id;

cin>>tahseen.marks;

cin>>faiyaz.per;

cout<<"Ashraf's id number is: "<< ashraf.id<<endl;

cout<<"Tahseen's marks is : "<<tahseen.marks<<endl;

cout<<"Faiyaz's precentage is:"<<faiyaz.per<<endl;

getch();

return 0;

}

In structure datatypes  we write the same program but only we use one variable instead of using different variable .


I hope this information is very helpful for u , if this helpful then please share it .

Md Ashraf

'KNOWLEDGE WITH ASHRAF' is the platform where you find all the type of knowledge especially on programming based. Our goal is to give you a deeper grasp of technology in specifics that will help you increase your knowledge.

Previous Post Next Post

Contact Form