March 19, 2008
torhu wrote:
> Frits van Bommel wrote:
>> BCS wrote:
>>> Steven Schveighoffer wrote:
>>>>
>>>> Now, here is the weird part.  The compiler does some magic with arrays.  If you are comparing an array with null, it changes the code to actually just compare the array pointer to null.  So, the the following code:
>>>>
>>>
>>> no this is the weird part:
>>>
>>> IIRC this passes.
>>>
>>> char* cp = cast(char*)null;
>>> char[] ca = ap[0..15];
>>> assert(ca.ptr == null && ca.length == 15);
>>
>> It does with DMD, if you s/ap/cp/, but I'm pretty sure what you're doing is invoking undefined behavior. Or at least it should be, but I can't seem to find any mention of it in the spec...
> 
> Can't see why that would be undefined.  It's pretty clear what it means.

Yes, it means constructing a completely invalid array. :)
Though perhaps it should only be undefined if you ever try to read or write the elements?

> Perhaps it should be an error when the compiler detects that you're setting .ptr to null but .length to nonzero.  But the compiler can't be expected to detect that in the general case, so it would be of limited usefulness.  A bit like disallowing comparing objects to 'null' with ==.

I didn't say it should be detected, only that the compiler should be well within its rights to make your code crash if you do that :P. An error message would also be nice of course, but by no means required.
Though as mentioned above, maybe the undefined behavior could be postponed until you actually try to read or write to the array.

It's quite similar to dereferencing null pointers: the compiler can refuse to compile code that tries to do it, but most compilers will just generate crashing code...
March 20, 2008
Frits van Bommel:
> It's quite similar to dereferencing null pointers: the compiler can refuse to compile code that tries to do it, but most compilers will just generate crashing code...

This can be acceptable for a little C compiler, like TinyCC, but D language is supposed to a safer and less bug-prone language. Otherwise it's just sugared C++ ;-)

Bye,
bearophile
1 2
Next ›   Last »