Disallow arrays as pointers

Salih Dincer salihdb at hotmail.com
Sat May 13 12:55:24 UTC 2023


On Monday, 31 October 2011 at 20:26:35 UTC, Timon Gehr wrote:
> On 10/31/2011 08:34 PM, bearophile wrote:
>> Kenji Hara (and the D community) is really good, he has 
>> already written a pull request with the bug fix:
>> https://github.com/D-Programming-Language/dmd/pull/483
>>
>> ---------------------
>>
>> Kenji Hara has fixed about 1/3 of the issue, so he asked me to 
>> split the but report, this is a spin off:
>> http://d.puremagic.com/issues/show_bug.cgi?id=6869
>>
>> In DMD 2.056 this code compiles:
>>
>> void main() {
>>     int[] a1 = [5, 4, 3];
>>     int* p1 = cast(int*)a1; // no compile error here
>> }
>>
>>
>> Similar code using user-created struct doesn't compile:
>>
>>
>> struct Foo {
>>      int* p;
>>      size_t n;
>> }
>> void main() {
>>      Foo f;
>>      auto x = cast(int*)f; // compile error here
>> }
>>
>
> That is not similar code. This is:
>
> struct Foo {
>     size_t length;
>     int* ptr;
>     T opCast(T: int*)(){return ptr;}
> }
>
> void main() {
>     Foo f;
>     auto x = cast(int*)f; // no compile error here
> }
>
>
>>
>> I don't see the need to accept this cast, because we have said 
>> that D arrays are not pointers, and allowing the array to 
>> pointer cast means introducing/leaving an useless special 
>> case, and in practice this special case is not useful because 
>> arrays have the ptr property:
>>
>
> extern(C) void foo(char* str);
> foo(cast(char*)"hello");
>
>
>>
>> struct Foo {
>>      int* p;
>>      size_t n;
>> }
>> void main() {
>>      Foo f;
>>      auto x = f.ptr; // OK
>> }
>>
>
> Actually compile error :o).
>
>>
>> So I think cast(int*)a1 should be forbidden.
>
> -1. I don't really see any point in disallowing it. It is an 
> explicit cast, not some kind of bug prone implicit behaviour.
>
>
>>
>> -----------------------
>>
>> The third part of the bug report was part of this older one:
>> http://d.puremagic.com/issues/show_bug.cgi?id=3971
>>
>> The idea is to forbid code like:
>>
>> void main() {
>>     int[3] a;
>>     a = 1;
>>     assert(a == [1, 1, 1]);
>> }
>>
>>
>> And require the square brackets every time an array operation 
>> is performed, for syntactic uniformity with the other vector 
>> ops, and to avoid mistakes:
>>
>>
>> void main() {
>>     int[3] a;
>>     a[] = 1;
>>     assert(a == [1, 1, 1]);
>> }
>>
>
> +1. That helps static type safety a bit and forces code to be 
> more readable.

I saw that it was closed today:

https://issues.dlang.org/show_bug.cgi?id=6869

Sorry for reviving an old thread. But I have to think that the 
problem will not be seen in newer versions?

Thanks...

SDB at 79


More information about the Digitalmars-d mailing list