Union: Reading from one data member of a union to write into another-Collection of common programming errors
I know that for the code below, “Illegal” below is undefined (while some compilers allow it), because union member “a” is active, and then we read from union member “b”. The question is, does the code in “AmILegal” fix it, or am I doing something scary and even more obscure? Can I use memcpy to achieve the same effect or is there another undefined behaviour I am invoking there?
EDIT: Maybe the example is not clear enough. All I want to do is activate the other member. So I am changing float to int. Although it seems dumb, it is closer to the real case. Read BELOW the code.
(Is it for some reason disallowed to copy one union member into another?)
struct Foo
{
union Bar
{
int a[4];
int b[4];
};
void this_is_Illegal()
{
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
std::cout
Originally posted 2013-11-09 22:55:58.