Something new for C?

Alex Colvin mac3n at babbage.acc.virginia.edu
Fri Nov 11 07:35:20 AEST 1988


> > way to do and have always wanted, was a precompiler command to allow me to
> > use the offset of an item into a structure. for example:

> #define  offset(type,field) ((unsigned int)&((type *)0)->field)

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) )

This gives you the offset in (void)s.  You could have it in (char)s or
(short)s instead.  The question is, why do you want this?  It doesn't
belong in the precompiler, since it has to know about size and alignment
constraints.  Explicit pointer subtraction is usually what I want.



More information about the Comp.lang.c mailing list