The C/C++ languages don't reorder struct members in memory and never insert padding before the first member. But if I have 2 structures that start with the same members, can I cast between them if I only access the common members? In other words, is struct layout greedy? My concrete case is casting between VIDEOINFOHEADER and VIDEOINFOHEADER2
The C++ standard contains the following statement which, however, only applies to unions (9.2 [class.member] paragraph 19):
If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.
I didn't see any other guarantee with respect to partially defined structures in either the C or the C++ standard. That doesn't mean it isn't there, though, just that I haven't found it with a quick scan of a couple of relevant sections.
Short answer: yes. Mostly.
Compilers cannot re-order struct members: true. I'm not so sure about the padding, IFAIR structure member alignment is implementation defined.
But, a compiler is consistent when laying out structures. It has to be, or you'd never be able to write and then read back structures to files. And most compilers use 'sane' rules for structure layout, so you can write from one program and read in with another, even if they are different compilers on different systems.
Most of the time. There are no exactly defined rules for structure layout. So occasionally you get bitten by relying on the "natural" layout to match, when it doesn't. But in this case, you should be safe.
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