"do ... while ((NULL + 1) - 1);" -- valid C?

Chris Torek chris at mimsy.UUCP
Thu Aug 10 09:58:14 AEST 1989


In article <696 at ftp.COM> wjr at ftp.COM (Bill Rust) writes:
>In my experience, NULL is always defined using the preprocessor line
>"#define NULL 0" (or 0L).

NULL may correctly (by the pANS) be defined as `(void *)0'.

>Since the while construct is relying on the fact NULL is, in fact, 0,
>doing NULL + 1 - 1 is ok.

It is *if* two conditions hold:

	0. NULL is `#define'd as an integral constant zero
	   rather than (void *)0, and
	1. the loop actually reads `while (NULL + 1 - 1)'.

The latter did not hold in the original example, which was

	do ... while ((s = index(s, ',') + 1) - 1);

The result of

	<expression yeilding non nil character pointer> + 1

is a pointer to the character `beyond the one returned', so that

	s = index("foo, bar", ',') + 1

winds up making s point to the space in "foo, bar"; but the
result of

	<expression yeilding nil character pointer> + 1

is not defined.%  On many machines it `just happens' to give the
address of byte number 1 in the machine; loading this into a machine
pointer register (e.g., for assignment to s) may cause a runtime trap.
In any case, its being undefined gives the system license to do
arbitrarily annoying things at this point.  The `-1' after this
is thus irrelevant: like Humpty Dumpty, once a pointer is broken,
not all the King's horses nor all the King's persons%% can put it
back together again.
-----
% So *that* is how you get a butterfly! :-)
%% non-sexist noun :-) [too bad about `King']
-- 
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