C and C++ could have non_nullable pointers, easily
Posted Aug 21, 2009 7:54 UTC (Fri) by
farnz (guest, #17727)
In reply to:
C and C++ could have non_nullable pointers, easily by nix
Parent article:
Null pointers, one month later
It's also impossible to verify the C type system; this doesn't stop
compilers from running. The trick is to go for a conservative assessment;
you're not interested in the choices "will sometimes be null/will never be
null", you're interested in "might or might not be null/will never be
null". The second is tractable; imagine an "ifnull( <ptrexpression>
) {
null-block } else { <ptrexpression is now nonnull> nonnull-block }".
By
requiring you to use ifnull to convert nullable pointers to nonnull
pointers whenever you might encounter them, the compiler can force you to
decide how you're going to handle unexpected nulls.
Whenever the compiler isn't sure that a pointer is nonnull, it gives a
compile-time error message. So, examples:
int func1( int *pointer )
{
return *pointer; // Compile error here - cannot deference a nullable
}
int func2( int * nonnull pointer )
{
return *pointer; // OK
}
int func3( int * pointer )
{
return func2( pointer ); // Compile error here - even if pointer is
actually non-null.
}
int func4( int * pointer )
{
ifnull( pointer )
return 0;
else
return func3( pointer ); // OK, but func3 still won't compile, as
other callers might use a null pointer.
}
int func5( int * pointer )
{
ifnull( pointer )
return 0;
else
return func2( pointer ); // OK
}
This forces you to handle nulls sanely at some point, or fail to
compile and link properly. Practical code handles nullness at boundary
points, and then passes nonnull pointers around the place, to code which
can assume that they're not null.
(
Log in to post comments)