I’m looking for some union examples, not to understand how union works, hopefully I do, but to see which kind of hack people do with union.
So feel free to share your union hack (with some explanation of course 🙂 )
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.
One classic is to represent a value of "unknown" type, as in the core of a simplistic virtual machine:
Using this you can write code that handles "values" without knowing their exact type, for instance implement a stack and so on.
Since this is in (old, pre-C11) C, the inner union must be given a field name in the outer
struct. In C++ you can let theunionbe anonymous. Picking this name can be hard. I tend to go with something single-lettered, since it is almost never referenced in isolation and thus it is always clear from context what is going on.Code to set a value to an integer might look like this:
Here I use the fact that
structs can be returned directly, and treated almost like values of a primitive type (you can assignstructs).