Disallow arrays as pointers
bearophile
bearophileHUGS at lycos.com
Mon Oct 31 12:34:59 PDT 2011
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
}
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:
struct Foo {
int* p;
size_t n;
}
void main() {
Foo f;
auto x = f.ptr; // OK
}
So I think cast(int*)a1 should be forbidden.
-----------------------
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]);
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list