Path: utzoo!attcan!uunet!cs.utexas.edu!tut.cis.ohio-state.edu!rutgers!gatech!bbn!ishmael!inmet!rgh From: rgh@inmet Newsgroups: comp.lang.c Subject: Re: offsetof() macro Message-ID: <20900005@inmet> Date: 25 Aug 89 19:37:00 GMT References: <70@motto.UUCP> Lines: 48 Nf-ID: #R:motto.UUCP:-7000:inmet:20900005:000:1755 Nf-From: inmet!rgh Aug 25 15:37:00 1989 >I think I heard somewhere of an offsetof() macro that was proposed for >the ANSI C Standard. If I've got it right, it would return the >number of bytes from the start of the structure to a given member, i.e. >the offset of the member within the structure. That's right. > 1. Am I right about such a macro being proposed? > 2. Was it accepted? Yes, it's part of the standard; it's defined in the header. > 3. What arguments does it take? What value does it return? >5. Can it be used in a static initializer, ex: > size_t mbr_off = offsetof(...); offsetof( type, member-designator) It expands to an integral constant expression that has type size_t (the same type that sizeof returns). Since it's a constant expression, it can be used as a static initializer. >4. Can it be written for all compilers? Can one version be portable, > or would different versions have to be written for different compilers? >5. If it could be portable, can you supply a definition. If not, can you > supply one which would work in most cases? One reason that it was standardized as a macro is that there didn't seem to be any definition to cite that would work on all implementations. These may work in a lot of implementations, and will not work in some: (starting out with #define offsetof(s_name, m_name) ) (size_t)&(((s_name*)0)->m_name) (size_t)(char*)&(((s_name*)0)->m_name) or, where X is some predeclared address (or possibly 0) and A(Z) is defined as ((char*)&Z): (size_t)( A( (s_name)X->m_name ) - A( X ) ) It's also possible to expand this to a special function call recognized by the compiler: the compiler can then just rummage through its symbol table & spit out the right answer. Randy Hudson uunet!inmet!rgh