C Union
Like structure, Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.
Advantage of union over structure
It occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structure
It can store data in one member only.
Defining union
The union keyword is used to define union. Let's see the syntax to define union in c.
Let's see the example to define union for employee in c.
C Union example
Let's see a simple example of union in C language.
Output:
employee 1 id : 1869508435employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only name will have actual value.
No comments:
Post a Comment