"headconst" dynamic arrays?
bearophile
bearophileHUGS at lycos.com
Wed Aug 31 02:42:07 PDT 2011
Christophe Travert:
> headconst seems a very useful thing.
In C you are allowed to write:
#include <stdio.h>
void foo(int * const arr, const int arr_len) {
// some code here...
arr_len += 1; // a bug
int arr2[] = {10, 20, 30, 40};
arr = arr2;
// some code here...
for (int i = 0; i < arr_len; i++)
arr[i]++;
for (int i = 0; i < arr_len; i++)
printf("%d ", arr[i]);
putchar('\n');
}
int main() {
int a[] = {1, 2, 3};
foo(a, 3);
return 0;
}
Here GCC 4.6.1 gives:
test.c: In function 'foo':
test.c:4:5: error: assignment of read-only parameter 'arr_len'
test.c:6:5: error: assignment of read-only parameter 'arr'
Dynamic arrays that don't change their length and don't allow rebinding, but allow changes in their contents, are useful. I use arrays every day in D and this desire arises now and then. It's hard to deny this.
But the point are: how much useful it is in D? Is the added language complexity worth it? Is it possible to design semantically sound conversions between the various kind of arrays? Is it possible/better a library solution for it?
> > void foo(int(const[]) arr)
> int(const[]) looks like a function signature, I would avoid it.
OK. The first syntax doesn't have this problem.
Bye,
bearophile
More information about the Digitalmars-d
mailing list