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

Doug Gwyn gwyn at smoke.BRL.MIL
Thu Aug 10 06:35:48 AEST 1989


In article <696 at ftp.COM> wjr at ftp.UUCP (Bill Rust) writes:
-In article <10684 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn) writes:
->In article <961 at virtech.UUCP> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
->>NULL + 1 is a valid operations, ...
->No!
-In my experience, NULL is always defined using the preprocessor line
-"#define NULL 0" (or 0L).

That's not always true, but anyway it's irrelevant...

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

The code example was adding 1 to the return value from strchr().
strchr() does not return a preprocessor macro; it returns a null macro
(when it doesn't return a pointer to a valid char object).  You are not
allowed to add 1 to a null pointer.  If you happen to get away with it,
you're just lucky; it's not correct code.

In any event, if you rely on NULL being defined (for example in <stdio.h>)
as the source character string "0", then you're asking for trouble, since
it can be defined as any valid form of null pointer constant, including
for example "((void*)0)".  Indeed, it's rather expected that standard-
conforming implementations are more likely to choose the latter form.
Your program may suddenly stop working when a new release of the compiler
is installed, or when you port it to another environment.



More information about the Comp.lang.c mailing list