S
Shao Miller
Shao Miller said:I guess a code generator could potentially accomplish something close
to this. I'd be interested in an algorithm which figures out the most
size-efficient ordering of the members, if anyone has one (or some
ideas for one).
Just sort the members into descending order of size.
I might be missing something... Suppose an 'int' has both size and
alignment of 4:
sizeof (struct {
char ca1[5]; /* 0 through 4 */
/* 3 bytes of padding; 5 through 7 */
int i; /* 8 through 11 */
/* No padding */
char ca2[3]; /* 12 through 14 */
/* 1 byte of padding; 15 */
}) == 16
The above is most likely, right? Whereas:
sizeof (struct {
int i; /* 0 through 3 */
/* No padding */
char ca1[5]; /* 4 through 8 */
/* No padding */
char ca2[3]; /* 9 through 11 */
/* No padding */
}) == 12
Right?
Yes. The advice has been shorted beyond usefulness. What I remember
being told (it was all fields round here, in those days) was to pack in
order of size (size being uses here as a proxy for alignment) treating
arrays as if they were just several fields of the array element type.
If it makes you feel better, I still hear "fields" in my head while
reading "members," on occasion.
Given your amendment to the previously advised strategy, can you think
of a situation where taking the result of that strategy and swapping the
first member out and injecting it as the last member could make a
difference for padding? For example:
struct foo {
int i;
char c;
/* Some padding, perhaps */
};
struct bar {
char c;
/* Some padding, perhaps */
int i;
};