Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Apr 16, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Unions in C++

I am trying to find some information on Unions in C++, specifically syntax and some type of example and perhaps a discussion as to when and why they are used.

Unions in C++ are mostly the same as unions in C. They provide an easy syntax that you can use to treat an area in memory as different variables. For example, say you had a list of items, and each item needed to hold either an integer or an array of 10 characters at any one time. You could create a structure that contained both data types, but that would waste memory if you used only one at a time. A better approach might be to declare a union.

union MyUnion {
   int i;
   char s[10];

This allows you declare a variable of type MyUnion, which you can treat either as an integer or a character array.
union MyUnion x;
x.i = 5;     // Use X as an integer
x.s[0] = 'x' // Use X as a char array
Both i and s occupy the same memory, which you can refer to using either syntax. Note that the space used by a union will be the size of the largest element. In this case, 10 bytes.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date