offsetof() macro
david.f.prosser
dfp at cbnewsl.ATT.COM
Sat Aug 26 02:21:38 AEST 1989
In article <70 at motto.UUCP> dave at motto.UUCP (dave brown) writes:
>My questions are:
>
>1. Am I right about such a macro [offsetof] being proposed?
Yes.
>2. Was it accepted?
Yes.
>3. What arguments does it take? What value does it return?
#include <stddef.h>
size_t offsetof(_type_, _member_);
where
if given ``static _type_ t;'', then ``&(t._member_)'' must
be a valid address constant.
>4. Can it be written for all compilers? Can one version be portable,
> or would different versions have to be written for different compilers?
There is no known valid C expression that meets all the requirements
for a portable offsetof macro. This is why it was standardized as
such, instead of giving enough power to constant expressions.
>5. Can it be used in a static initializer, ex:
>
> size_t mbr_off = offsetof(...);
Yes.
>5. If it could be portable, can you supply a definition. If not, can you
> supply one which would work in most cases?
The Rationale suggests some possibilities:
(size_t)&(((_type_*)0)->_member_)
(size_t)(char *)&(((_type_*)0)->_member_)
(size_t)(((char *)&(((_type_*)0)->_member_))-((char *)0))
(size_t)(((char *)&(((_type_*)&X)->_member_))-((char *)&X))
where in the last X is some predeclared static object address.
None of these are portable.
Dave Prosser ...not an official X3J11 answer...
More information about the Comp.lang.c
mailing list