offsetof() macro

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Aug 26 21:40:58 AEST 1989


In article <70 at motto.UUCP> dave at motto.UUCP (dave brown) writes:
>1. Am I right about such a macro being proposed?
>2. Was it accepted?

Yes.

>3. What arguments does it take?  What value does it return?

#include <stddef.h> defines the offsetof macro, which has two arguments:
the first designates a structure type, and the second is a member
designator.  It returns the offset (in bytes) of the member of such a
structure.

>4. Can it be written for all compilers?  Can one version be portable,
>   or would different versions have to be written for different compilers?

In general, some help from the compiler is required.  This could take the
form of a keyword __offsetof in terms of which the offsetof macro could
be defined.

An almost-portable definition is possible, using a single extern struct
and a lot of type casts and so forth.  You may also have seen a definition
that involves using 0 as a pseudo-structure pointer; that's less likely to
work.

>5. Can it be used in a static initializer, ex:
>	size_t mbr_off = offsetof(...);

Frankly, I don't recall, and my copy of the standard is not at hand.

>5. If it could be portable, can you supply a definition.  If not, can you
>   supply one which would work in most cases?

I'm sure you'll get zillions of suggestions here..



More information about the Comp.lang.c mailing list