Understanding Unions

I understand how to use a union, for the most part. From what I understand, a union is a shared memory address for different types? Does that mean I could make a member for my union for every datatype, then put any kind of type I want in it without worrying about whether it would fit?

For example, my program to test this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
union myunion {
	int integer;
	float floatingpoint;
	char character;
};
int main () {
	myunion union_a;
	int Nt = 25; //I like to create creative with the names, at least in my own personal hobbying
	float flote = 12.69;
	char shar = 'g'; //two extra variables for testing the union, for quick edits
	union_a.integer = flote; //put a float into the union, thinking the union will assume the datatype without me having to specify one for it. i think this because the union shares memory with all the members. so if I put an int in there and there was an int and a float, then the computer should assume that I want the int put into the int member, not the float.
	cout<<"union.integer is: "<<union_a.integer; //access any member of the union to get the value, because the data needed will be assumed?
	cin >> Nt; //this is the only way I know how to make the program wait for me to read it :)
	return 0;
}


Would this
Last edited on
union_a.integer is an int. You can not store any other type of data in it (above it is being implicitly casted.) A union allows you to store one of many types of data in a single memory location. You still need to tell the compiler what type of data you are trying to receive from that memory.
when you do a sizeof of a union it will be the size of the largest data type in the union. In your case 4 (float and int are both 4, char = 1). All of the variables in the union start at the same address and overlap each other. Yes you can assign a float to an int through a union but your data will be converted (in this case truncated). With casting in C/C++ you can assign anything to anything but you might just end up with garbage...

Like they say in C you can shoot yourself in the foot. In C++ you can create 10 instances of yourself and shoot your foot 10 times...
Topic archived. No new replies allowed.