A
Adrian
I remember from C that you are not supposed to access different
members of a union at the same time?
It seems to say the same thing in the C++ standard (9.5.1)
"In a union, at most one of the data members can be active at any
time, that is, the value of at most one of the data members can be
stored in a union at any time."
What does it mean by "any time" forever, block scope, function scope?
So is any of the code below in this simplistic example valid? I know
it works on any implementation I've used but that doesn't make it
correct
PS The whole point of this is to make some IPC messaging code more
readable
PPS I know about struct padding ;-)
#include <iostream>
union IP {
unsigned long plain;
char dotted[4];
};
void fill_by_ref(IP &ip);
int main(int argc, char *argv[])
{
IP ip;
ip.dotted[0]=127;
ip.dotted[1]=0;
ip.dotted[2]=0;
ip.dotted[3]=1;
std::cout << "ip.plain=" << ip.plain << std::endl; // Illegal I
assume from 9.5.1?
IP ip2;
fill_by_ref(ip2);
std::cout << "ip2.plain=" << ip2.plain << std::endl; // Is this any
better?
IP ip3(ip);
std::cout << "ip3.plain=" << ip3.plain << std::endl; // Or is this
any better?
return 0;
}
void fill_by_ref(IP &ip)
{
ip.dotted[0]=127;
ip.dotted[1]=0;
ip.dotted[2]=0;
ip.dotted[3]=1;
}
members of a union at the same time?
It seems to say the same thing in the C++ standard (9.5.1)
"In a union, at most one of the data members can be active at any
time, that is, the value of at most one of the data members can be
stored in a union at any time."
What does it mean by "any time" forever, block scope, function scope?
So is any of the code below in this simplistic example valid? I know
it works on any implementation I've used but that doesn't make it
correct
PS The whole point of this is to make some IPC messaging code more
readable
PPS I know about struct padding ;-)
#include <iostream>
union IP {
unsigned long plain;
char dotted[4];
};
void fill_by_ref(IP &ip);
int main(int argc, char *argv[])
{
IP ip;
ip.dotted[0]=127;
ip.dotted[1]=0;
ip.dotted[2]=0;
ip.dotted[3]=1;
std::cout << "ip.plain=" << ip.plain << std::endl; // Illegal I
assume from 9.5.1?
IP ip2;
fill_by_ref(ip2);
std::cout << "ip2.plain=" << ip2.plain << std::endl; // Is this any
better?
IP ip3(ip);
std::cout << "ip3.plain=" << ip3.plain << std::endl; // Or is this
any better?
return 0;
}
void fill_by_ref(IP &ip)
{
ip.dotted[0]=127;
ip.dotted[1]=0;
ip.dotted[2]=0;
ip.dotted[3]=1;
}