Assume I have
union myUnion
{
short s;
long l;
char* cstr;
};
Now assume I get a pointer to a myUnion and know at compile type which "type" it is.
Is it save/correct to do this:
short s = *(static_cast<short*>(u)); // where u is a pointer to myUnion
I kinda think it is because if I understand unions in c++ correctly, for myUnion u
&u == &(u.s) == &(u.l) == &(u.cstr)
but I'm not sure and I fear that by doing this I get a ride to undefined behaviour land...
Thanks in advance for any input!
edit just to clarify: I know how to use a union "the normal way" (short s = u.s). I know that unions are there because of C and you probably don't want to use unions in moden c++ code.
I am asking because I am interested if the "static_cast" above is "bad".