[comp.lang.c] Arithmetic on NULL

karl@haddock.UUCP (09/17/87)

In article <48400001@tub.UUCP> cabo@tub.UUCP writes:
>While I agree that "char *p = 0; p++;" should not be allowed by the standard,
>I see some benign applications for constant expressions involving null
>pointers, e.g.
>	(char *)&((struct foo *)0)->bar - (char *)&((struct foo *)0)->baz

In ANSI C, the correct way to write the above is "offsetof(struct foo, bar) -
offsetof(struct foo, baz)".  Since this is guaranteed to work, your example is
not evidence of a need for NULL pointer arithmetic.

Now, it may well be the case that "offsetof" is defined in <stddef.h> to
expand into the above mess, on machines where it happens to work.  That's
okay; the use is portable even though the implementation is not.

I expect that machines with non-flat address spaces and weird representations
of NULL may have to implement "offsetof" as a builtin.  That's okay too.

Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint