Difference between Structure and Union


Structure: Structure is a user defined data type in c that combined different kind of data items into a single lock of memory. Structure variable can contain more than one data item of different kind under a single name. In structure each item get separate memory location. A structure data type is used when a lot of data needs to combine such as if you want to create a database about details under a single entity. You can do it by using structure data type.
To declare structure you need to use strict keyword. Which tells the compiler that a structure data type has been declared.
Struct Student{
String name;
String age;
String address;
String class;
……….}std1, std2
Here we create a structure to store the data of a student. The declaration is closed by a semicolon we also created variables std1 and std2 which are the type of student we can also create the variables separately.
Student std1, std2;

Union: Union is also a user defined data type that combines different kind of data items in the same memory location. In union data type all the items get the same memory location. Is you want to use the same memory location for multiple items the you can do it easily by using union data type. When a union data type is declared the compiler allocates the largest size available memory so that the size of union is equal to the largest size of data member. A union allows multiple data items but only one item can contain a value at any given instance of time.
To declare a union you have to use the union keyword which tells the compiler that a compiler data type has been declared.
Union union_name{
Int a;
Char c;
Float f;
}un1, un2;
Here we create a union data type, we also created two variables named un1, un2 which are the type of union_name we can also create the Variable Separately.
union_name un1, un2;



Structure Union
1. Uses different memory location. 1. Uses same memory location.
2. Can contain multiple values at a time. 2. Can contain a single value at a time.
3. Size is equal to the sum of the size of all items. 3. Size is equal to the size of the largest member.
4. Provides single view of each location. 4. Provides multiple views of a single location.
5. An anonymous structure can not be declared. 5. An anonymous union can be declared.
6. Struct keyword is used to declare a structure. 6. Union keyword is used to declare a union.
7. Supports flexible array. 7. Does not flexible array.


Similarities

  • Both the structure and union are user defined data type.
  • Both contain different kinds of data items.
  • Both can be passed to a sanction using both calls by value and call by reference menthol.
  • Both structure and union have the same way of declaring itself.
  • Both structure and array can be in the form of any data type.



Contributed By: Romana Rahman Ema