offsetof() macro

rgh at inmet rgh at inmet
Sat Aug 26 05:37:00 AEST 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 <stddef.h> 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



More information about the Comp.lang.c mailing list