Difference between Structure and Union in C Program

CServer Side ProgrammingProgramming

In C we have container for both i.e. for same type data and multiple type data. For storage of data of same type C provides concept of Array which stores data variables of same type while for storing data of different type C has concept of structure and union that can store data variable of different type as well.

Since both Structure and Union can hold different type of data in them but now on the basis of internal implementation we can find several differences in both of these containers.

Following are the important differences between Structure and Union.

Sr. No.KeyStructureUnion
1DefinitionStructure is the container defined in C to store data variables of different type and also supports for the user defined variables storage.On other hand Union is also similar kind of container in C which can also holds the different type of variables along with the user defined variables.
2Internal implementationStructure in C is internally implemented as that there is separate memory location is allotted to each input memberWhile in case Union memory is allocated only to one member having largest size among all other input variables and the same location is being get shared among all of these.
3SyntaxSyntax of declare a Structure in C is as follow :
struct struct_name{
   type element1;
   type element2;
   .
   .
} variable1, variable2, ...;
On other syntax of declare a Union in C is as follow:
union u_name{
   type element1;
   type element2;
   .
   .
} variable1, variable2, ...;
4SizeAs mentioned in definition Structure do not have shared location for its members so size of Structure is equal or greater than the sum of size of all the data members.On other hand Union does not have separate location for each of its member so its size or equal to the size of largest member among all data members.
5Value storageAs mentioned above in case of Structure there is specific memory location for each input data member and hence it can store multiple values of the different members.While in case of Union there is only one shared memory allocation for all input data members so it stores a single value at a time for all members.
6InitializationIn Structure multiple members can be can be initializing at same time.On other hand in case of Union only the first member can get initialize at a time.
raja
Published on 10-Jan-2020 10:17:01
Advertisements