Consider the following struct:
struct Vector4D
{
union
{
double components[4];
struct { double x, y, z, t; } Endpoint;
};
};
It seems to me that I have seen something similar in WinApi's IPAddress struct. The idea is to give me the possibility to use the array components both by index and by name, for example:
Vector4D v;
v.components[2] = 3.0;
ASSERT(v.Endpoint.z == 3.0) //let's ignore precision issues for now
In the C++ standard there is a guarantee that there will be no "empty" space at the beginning of a POD-struct, that is, the element x will be situated right in the beginnig of the Endpoint struct. Good so far. But I don't seem to find any guarantees that there will be no empty space or padding, if you will, between x
and y
, or y
and z
, etc. I haven't checked out the C99 standard though.
The problem is that if there is an empty space between Endpoint struct elements, then the idea will not work.
Questions:
Am I right that there indeed is no guarantee that this will work either in C or C++.
Will this practically work on any known implementation? In other words, do you know of any implementation where this doesn't work?
Is there any standard(I mean not compiler-specific) way to express the same idea? Maybe the C++0x alignment features might help?
By the way, this isn't something I am doing in production code, don't worry, just curious. Thanks in advance.
.z()
instead of just .z
)Most compilers should support squashing a structure using a pragma or an attribute. #pragma pack
for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With