Thursday, February 4, 2016

Difference between structure and union



Both structure and union are user defined data types!
 Structure is a user defined data type where we can store many related different data types at a single place in memory!for example if we want to store the student in memory then we have to store roll number name and group and grade and so on .  This can be accomplished using struct data type.

struct variable name
{
  data type data member1;
  data type data member2;
  data type data member3;
-------
}variables;

example:
struct student
{
  int rollno;
 char name[20];
 char group[10];
 float grade;
}s1,s2,s3;  /* s1 s2 s3 are student1 student2 and student3*/

the student data type occupies 36 bytes[2+20+10+4];

The same we can do with union data type
union variable name
{
  data type data member1;
  data type data member2;
  data type data member3;
-------

}variables;

example:
union student
{
  int rollno;
 char name[20];
 char group[10];
 float grade;
}s1,s2,s3;  /* s1 s2 s3 are student1 student2 and student3*/

the only difference is using struct it takes 36 bytes of memory. but with union it takes only 20 bytes of memory. union data type takes and fixes the size to largest data type available in struct! in the above declaration  name data member takes 20 bytes.

















Difference between structure and union! Struct and union data type , size of struct and size of union  , user defined data types, enum data types, data types classification, arrays structures union boolean data types. program using struct and union student data base program using struct and union

No comments:

Post a Comment