#defining NULL as (-1) in stdio

Martin Minow THUNDR::MINOW ML3-5/U26 223-9922 minow at thundr.dec.com
Thu Jun 23 01:09:00 AEST 1988


In a recent posting, sun!gorodish!guy comments on another posting:

>> ...if "0" does refer to the null pointer, why do some systems have #define
>> NULL (-1) in stdio?
 
>Because the implementors were ignorant.  Any language implementation that
>defines NULL as -1, and purports to be an implementation of C, is broken.

While this is true as far as it goes, the documentation for early Unix
systems were not always careful to explain that NULL was zero.  For
example, the description of fopen() in 4.1bsd states that it returns
"the pointer NULL" if the file cannot be accessed.  It does not, however,
note that the value of NULL is zero.  One could, therefore, conceive of
a properly-defined Unix stdio package where the error return value from
fopen() was non-zero.

This means that the proper way to open a file is

	if ((fd = fopen(...)) != NULL) {
	    ...
	}

Of course, the shave-a-byte-off-the-source-code weenies would probably
write
	if ((fd = fopen(...)) {
	
which requires the error value to be zero and all stdio implementations
I'm familiar with do define it as zero.

Somewhere in the distant past, I recommended to the Ansi committee that
NULL should have been made a reserved word with undefined content.  They
rejected this request, as they didn't want to add any reserved words to
the language.

Martin Minow
minow%thundr.dec at decwrl.dec.com



More information about the Comp.lang.c mailing list