[Aldor-l] alignof
Stephen Watt
watt at scl.csd.uwo.ca
Fri Mar 21 19:22:46 EDT 2008
On Fri, Mar 21, 2008 at 11:22:36PM +0100, Pippijn van Steenhoven wrote:
> First of all, it is not important whether or not there is an example. The
> compiler is free to add padding to a struct { char a; short b; }; and then the
> code is broken. On x86, it would make sense to align the short to 4 bytes and
> the struct itself, too, leading to an alignof (that struct) of 0. I can
> probably live with it as long as no issues arise. The problem is really just,
> the code is broken and it would be good if a better alternative was found.
>
> --
> Pippijn van Steenhoven
On 3/21/08, Pippijn van Steenhoven wrote:
>
> I keep wondering what to do with this:
>
> # define alignof(T) (sizeof(struct {char a; T b;}) - sizeof(T))
>
> as it's incorrect. When the compiler adds padding to the structure,
> this macro may return a negative value, breaking everything.
-----------------------------------------------------
Pippijn,
As Gabriel pointed out, we can have conditional implementation in terms of
__alignof__. There will be some platforms without it, however, so this
discussion remains useful.
The reason I ask for an example where it is wrong is because I don't understand
your statement that the macro can return a negative value.
Can you please explain?
I do not recall whether the C standard allows the compiler to re-order
fields of a structure.
If the compiler does not re-order fields, then I believe
sizeof(struct {char a; T b; }) is strictly greater than sizeof(T)
so the value of the macro will always be positive.
If the compiler can re-order fields, then I believe
sizeof(struct {char a; T b; }) is greater than or equal to sizeof(T)
so the value of the macro will always be non-negative, but possibly zero.
So if this is what you are worried about, it could probably be fixed as
something along the lines of
if have __alignof__
use that
else
correct alignof = max(old alignof, 1)
-- Stephen
More information about the Aldor-l
mailing list