Fixing C's Biggest Mistake
Sebastiaan Koppe
mail at skoppe.eu
Sat Dec 31 07:55:01 UTC 2022
On Saturday, 31 December 2022 at 06:34:38 UTC, Walter Bright
wrote:
> NonNull pointers:
>
> int* p = ...;
> nonnull int* np = isPtrNull(p) ? fatalError("it's null!") : p;
> *np = 3; // guaranteed not to fail!
>
> Null pointers:
>
> int* p = ...;
> *p = 3; // seg fault!
>
> Which is better? Both cause the program to quit on a null
> pointer.
In a larger program the first one allows the programmer to do the
check once and rely on it for the remainder of the program.
Essentially it leverages the type system to make invalid state
unrepresentable. This simplifies subsequent code.
It is very much similar to representing a phonenumber using
either a string or a dedicated phonenumber type. The way you
construct an instance of the phonenumber type is through a check,
and any function accepting it can rely on it. In contrast, if one
uses strings to pass around phonenumbers, you will need so many
checks everywhere you likely forget one.
>
> Having a hardware check is perfectly valid for checking things.
>
Not all targets have said check though.
More information about the Digitalmars-d
mailing list