Something new for C?
Chris Torek
chris at mimsy.UUCP
Fri Nov 11 12:33:15 AEST 1988
>>#define offset(type,field) ((unsigned int)&((type *)0)->field)
In article <399 at babbage.acc.virginia.edu> mac3n at babbage.acc.virginia.edu
(Alex Colvin) writes:
>This works by casting a pointer to an unsigned. That sometimes isn't a
>good idea. To make integers out of pointers, it's best to subtract.
>
>#define offset(type,field) ((void *)&((type *)0)->field - (void *)((type *)0))
The advice above is reasonable; the implementation is not. You may not
perform arithmetic on pointers to void. This is considered a feature.
The dpANS provides a (compiler-dependent!) macro called `offsetof' that
might be defined as
#define offsetof(t, f) ((char *)&((t *)0)->f - (char *)(t *)0)
or more simply as
#define offsetof(t, f) ((int)&((t *)0)->f)
or as some horrible internal compiler reference:
#define offsetof(t, f) __C_compiler_internal_label__offset_of(t, f)
Various restrictions in the dpANS make all of these definitions
suspect-at-best, but one (whatever it might be) is to be provided
and called `offsetof'.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list