Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!cbnewsl!dfp From: dfp@cbnewsl.ATT.COM (david.f.prosser) Newsgroups: comp.lang.c Subject: Re: offsetof() macro Message-ID: <1629@cbnewsl.ATT.COM> Date: 25 Aug 89 16:21:38 GMT References: <70@motto.UUCP> Reply-To: dfp@cbnewsl.ATT.COM (david.f.prosser) Organization: AT&T Bell Laboratories Lines: 47 In article <70@motto.UUCP> dave@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 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...