dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Unions in C++

Question:
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.

Answer:
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.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date