ANSI C
karl at haddock
karl at haddock
Sat Aug 16 10:32:00 AEST 1986
haddock!karl (Karl Heuer) writes:
>> The constant 0 used in a pointer context still denotes the null pointer,
>> but an integer variable whose value happens to be zero need not produce
>> the null pointer when cast.
sun!guy (Guy Harris) replies:
>Yes. This may be considered questionable, since, given the declarations
>"int i; char *p;" the statements "i=1; p=i;" and "p=1;" should be expected
>to stuff the same value into "p", but the statements "i=0; p=i"; and "p=0;"
>need not stuff the same value into "p" - i.e., the constant expression 0 is
>treated differently when converting to a pointer type than any other
>integral expression.
In particular, "p = i = 0;" is a loser! (I don't expect many programs do
this, since it produces a pointer/integer conflict.)
>Unfortunately, there's not a hell of a lot you can do about it. If C had a
>keyword "nil" that would, when it appears in an expression, be converted to
>a null pointer of the appropriate type (as the constant expression 0 is
>converted now), this problem wouldn't occur; however, it's a little to late
>to fix this now, given all the code out there that uses 0 for this.
It's not too late. In the first place, NULL already exists for this purpose
(though some people insist on using it as a synonym for '\0' too!) If zero-
in-pointer-context henceforth produces a warning message, people will convert
their programs to use NULL instead. If the feature then goes away, only the
programmers who ignored the warning will be burned. (This is not necessarily
a good idea, but it *can* be done.) NULL would presumably be changed from
"0" to an implementation-defined constant like "(void *)0xF0000000".
>"Fixing" it the other way, by having any integral expression with the value
>0 convert to a null pointer, would ... surprise some code that does want to
>grab a pointer value [as int] and then stuff the value back into the
>pointer, if a pointer value of all zero bits is a valid pointer.
Hmm, there's a similar problem without the full-check conversion. If the
constant zero is converted into a null pointer constant, and zero is a valid
address, and something of interest is at that absolute address, how do I
reference it? "x = *(int *)0" will try to dereference NULL instead of 0, and
"i = 0; x = *(int *)i" will undoubtable fail on some optimizing compilers.
Karl W. Z. Heuer (ihnp4!ima!haddock!karl), The Walking Lint
More information about the Comp.lang.c
mailing list