A
Arthur J. O'Dwyer
As far as I know, C89/C90 did not contain the
now-standard offsetof() macro.
Did C89 mandate that structs had to have a consistent
layout? For example, consider the typical layout of
the following structure:
struct weird
{
int x; /* sizeof(int)==4 here */
double y; /* sizeof(double)==8 here */
int z;
};
Now, let's suppose that the target architecture has typical
80x86 alignment requirements, where 'int' aligns on 4-byte
boundaries and 'double' on 8-byte boundaries.
A C99 compiler might produce a layout that looked like
this:
|_x__|####|___y____|_z__|####|
sizeof (struct weird) == 24 bytes
But could a C89, pre-offsetof() compiler decide to make
the layout of the struct vary, like this:
|_x__|####|___y____|_z__| on 8-byte alignment
|_x__|___y____|####|_z__| on 4-byte alignment
sizeof (struct weird) == 20 bytes
Note that the relative ordering of the members is
preserved; each 'struct weird' has the same size in
bytes; and all objects are properly aligned for their
type. But the "weird" ordering has saved us 4 bytes
per structure!
Does C89 allow this, or is it disallowed by something
in that standard? If so, what?
TIA,
-Arthur
now-standard offsetof() macro.
Did C89 mandate that structs had to have a consistent
layout? For example, consider the typical layout of
the following structure:
struct weird
{
int x; /* sizeof(int)==4 here */
double y; /* sizeof(double)==8 here */
int z;
};
Now, let's suppose that the target architecture has typical
80x86 alignment requirements, where 'int' aligns on 4-byte
boundaries and 'double' on 8-byte boundaries.
A C99 compiler might produce a layout that looked like
this:
|_x__|####|___y____|_z__|####|
sizeof (struct weird) == 24 bytes
But could a C89, pre-offsetof() compiler decide to make
the layout of the struct vary, like this:
|_x__|####|___y____|_z__| on 8-byte alignment
|_x__|___y____|####|_z__| on 4-byte alignment
sizeof (struct weird) == 20 bytes
Note that the relative ordering of the members is
preserved; each 'struct weird' has the same size in
bytes; and all objects are properly aligned for their
type. But the "weird" ordering has saved us 4 bytes
per structure!
Does C89 allow this, or is it disallowed by something
in that standard? If so, what?
TIA,
-Arthur