Byte alignment in union

L

llewelly

Gianni Mariani said:
...


You may not store something in

...

There is a significant amount of code in existance that does otherwise
that seems to behave in a well defined manner.

Such a thing is well-defined only iff the union contains several
POD-structs with common initial sequences, and only the common
initial sequences are used interchangeably.

There is a lot of union-using code which violates the standard, and
most of it breaks when certain modern optimizations, e.g. gcc's
-fstrict-aliasing, are enabled. (btw, this optimization was
implemented by gcc in 1999, but only now is it on by default at
any normal optimization level, due to fears about how much code
might break.)
 
M

Michiel Salters

My take: The Standard doesn't forbid an implementation from padding
member fields beyond alignment requirements, but common sense does.

A POD struct can *always* be implemented in terms of an array of its
largest member, and any further padding is just a waste of space.

That is, unless a type needs more padding to work efficiently than to
work correctly. But then, why extraneously pad a struct and not an
array? And how do you explain that to the guy who needs a massive
array of structs? If you're going to choose between time and space,
stick to your choice in all cases. Maybe give the user the right to
choose, but don't mix-and-match (unless you want to add that as an
optional extension, of course).

That's the close to the point, extensions. A compiler vendor could
have two switches for alignment, one controlling array alignment
and one controlling alignment within a structure. The standard
allows any setting i.e. for any pair of padding parameters that
compiler could be conformant. Obviously compiler switches aren't
covered by the standard, but the result is.
So, I wouldn't count on this behavior, but (if I cared enough) I'd
look into filing a DR. The only problem is that it's hard to argue
that "because I want to be able to do weird stuff with unions,
structs, and arrays" is sufficient reason to alter the core language.

Filing a DR isn't going to work. Even when a committee member agrees
with the intent of a DR the DR isn't suddenly fixed. The committee
needs a solution to the DR to vote on. If you care enough, write
a proposal for C, join WG14 and get it accepted there. Once it's
in C, getting the proposal through to C++/WG21 is a lot easier.

Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top