That requires protected memory and zero isn’t unique in that. The OS could make many more addresses special in that respect.
On most (¿all?) OSes it also won’t work if you make your structure large enough, and try to access a field at an offset (let’s say your OS makes the first 4kB of memory unaccessible by user code, you declare p as a pointer to an array of a million integers, but don’t initialize it and then access p[999999])
It also is an implementation detail. A compiler could compile something like Either[Foo,Null] (with Foo a type and Null a value or a type that’s guaranteed to have only one instantiation) to either a pointer to a Foo or a null bit pattern.
Even better, an implementation _could_ hide the “it’s not a Foo” bit in any unused bit inside a Foo object (say inside padding, or in a byte storing an enumeration that has less than 256 values)
(aside: are there languages that represent Either[FooPtr,BarPtr] as a pointer-sized field holding either a pointer to a Foo or one plus a pointer to a Bar, using the fact that top bits of pointers to objects always are zero to discriminate between the two?)
nullable pointers can take up the same amount of memory at runtime, vs optionals that can be nested, so you need to represent .none from .some(.none), which means you need at least another bit
gavinray|3 years ago
There's safe-access "?." and ".let", which only fires if the receiver is non-nullable
WalterBright|3 years ago
My unpopular opinion is that null pointers are unfairly maligned.
Someone|3 years ago
On most (¿all?) OSes it also won’t work if you make your structure large enough, and try to access a field at an offset (let’s say your OS makes the first 4kB of memory unaccessible by user code, you declare p as a pointer to an array of a million integers, but don’t initialize it and then access p[999999])
It also is an implementation detail. A compiler could compile something like Either[Foo,Null] (with Foo a type and Null a value or a type that’s guaranteed to have only one instantiation) to either a pointer to a Foo or a null bit pattern.
Even better, an implementation _could_ hide the “it’s not a Foo” bit in any unused bit inside a Foo object (say inside padding, or in a byte storing an enumeration that has less than 256 values)
(aside: are there languages that represent Either[FooPtr,BarPtr] as a pointer-sized field holding either a pointer to a Foo or one plus a pointer to a Bar, using the fact that top bits of pointers to objects always are zero to discriminate between the two?)
superlopuh|3 years ago