Eric Sosman said:
Yah. It is "guaranteed to work" in the sense that it will
compute an alignment that suffices for type T. As you point out,
though, it is not guaranteed to compute the *minimal* alignment
for type T. (On the other hand, "minimal alignment" is something
that -- as far as I can see -- is not testable in a conforming C
program.)
Right, the result of 'alignof' suffices. When I said the definition
isn't guaranteed to work what I meant was it isn't guaranteed to
produce a result that divides sizeof(T), which the "real" alignment
must do. Similarly using the GCD will produce a result that is
guaranteed to divide sizeof(T), is a multiple of the "real" alignment,
and is the best information available under the circumstances.
I agree with your comment that the "minimal alignment" of a type (the
same as what I called "real" alignment) is not discoverable in a
conforming C program (assuming that it's greater than 1 of course).
GCD might improve the answer, but it still isn't guaranteed
to be minimal -- also, it's difficult to compute in the form of
a constant expression, which is often desirable in contexts where
games of this sort are played. Myself, I generally stick with
sizeof(T) as a reasonable approximation to the alignment; it may
well overstate the requirement, but not by much (so long as I
avoid using really silly types for T).
Yes, I agree, at least for base types; for struct's or arrays it
seems like it can be worthwhile in some circumstances to get a better
estimate using an alignof-like technique.
You're definitely right that it's difficult to compute GCD in the form
of a constant expression. I played around with various approximate
forms, hoping that some approximate form would produce accurate
results in most circumstances of practical interest, but it's not that
easy. So if one wants a "compile time" result I think the best way
to get it is to compile a small program that computes the answer and
feed that back in to a subsequent compile via a generated header or
something similar. What a pain.
Just out of curiosity, has there been any serious discussion about
having an 'alignof( type name )' capability be added to the standard?