Recently I am working on windows and I found that lot of data structures are defined as struct with union as member variables. Example of this would be EVT_VARIANT in Windows.
I failed to understand what is the purpose behind this.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When a
structcontainsunionmembers it’s generally done as a space saving mechanism. If thestructcan be of certain sub-types by which only certain members are valid then aunionis a good way to not waste space.For example
In this scenario I’ve defined a
structNumber which can have type types of numeric values: floating point and integer. It’s not valid to have both at the same time so rather than waste space by having both members always defined I created aunionwhich makes the storage of both equal to the size of the biggest.Sample Usage of Above as requested