Site icon Pathshala Nepal

Differences between Structure and union

What are the different between Structure and Union?


2 Answers


S.N Structure S.N Union
1. You can use a struct keyword to define a structure. 1. You can use a union keyword to define a union.
2. Every member within structure is assigned a unique memory location. 2. In union, a memory location is shared by all the data members.
3. Changing the value of one data member will not affect other data members in structure. 3. Changing the value of one data member will change the value of other data members in union.
4. The total size of the structure is the sum of the size of every data member. 4. The total size of the union is the size of the largest data member.
5. It occupies space for each and every member written in inner parameters. 5. It occupies space for a member having the highest size written in inner parameters.
6. You can retrieve any member at a time. 6. You can access one member at a time in the union.
S.N Structure Union
1. It occupies the total memory space required by all its members. It occupies the memory space equal to the requirement of its largest member.
2. It requires a large memory space. It requires a smaller memory space.
3. It can take part in a complex data structure. It cannot take part in complex data structures.
4. Keyword struct is required to declare structure A keyword union is required to declare a union.
5.

eg:

struct student{
char name[20];
int age;
};
struct s1;

eg:

struct student{
char name[20];
int age;
};
union s1;

 

6. The above declaration reserves 20+2=22 Bytes memory space. The above declaration reserves 20 Bytes memory space.
7.

Syntax of structure:

struct user_defined_name
{
data_type member1;
data_type member2;
...........................
data_type member;
};
struct user defined_name
var1, var2............

Syntax of the union:

union user_defined_name
{
data_type member1;
data_type member2;
...........................
data_type member;
};
struct user defined_name
var1, var2............

Topics from Computer
Related Questions