Why is this allowed

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jun 30 16:36:45 UTC 2020


On Tue, Jun 30, 2020 at 04:22:57PM +0000, JN via Digitalmars-d-learn wrote:
> Spent some time debugging because I didn't notice it at first,
> essentially something like this:
> 
> int[3] foo = [1, 2, 3];
> foo = 5;
> writeln(foo);   // 5, 5, 5
> 
> Why does such code compile? I don't think this should be permitted,
> because it's easy to make a mistake (when you wanted foo[index] but
> forgot the []).  If someone wants to assign a value to every element
> they could do foo[] = 5; instead which is explicit.

File a bug?

I suspect that one potential reason is that nasty misfeature of static
arrays implicitly converting to a slice of itself, so `foo = 5;` is in
some sense being translated as `foo[] = 5;`.

(And on that note, this implicit static -> dynamic array conversion is
seriously a nasty misfeature that ought to be killed with fire. It leads
to bugs like this:

	struct Database {
		int[] data;
		void set(int[] _data) {
			data = _data;
		}
	}
	void myFunc(ref Database db) {
		int[3] x;
		db.set(x);	// oops
	}
)


T

-- 
Once the bikeshed is up for painting, the rainbow won't suffice. -- Andrei Alexandrescu


More information about the Digitalmars-d-learn mailing list