Error message for unreachable code

Oskar Linde oskar.lindeREM at OVEgmail.com
Fri Apr 7 05:56:54 PDT 2006


Hi,

The following code:

void main() {
	char[0] x;
	if (x.length > 0) {
		char y = x[0];
	}
}

Refuses to compile with the following error message:

zeroarray.d(4): array index [0] is outside array bounds [0 .. 0]

And before someone asks why I would declare a zero length static array I 
  better tell that this is occurs in template code where the type of x 
can be both static and dynamic arrays.

My current workaround looks like this:

template ZeroLengthStaticArray(X:X[0]) {
	alias X ZeroLengthStaticArray;
}

void main() {
	char[0] x;
	static if(!is(ZeroLengthStaticArray!(typeof(x)))) {
		if (x.length > 0) {
			char y = x[0];
		}
	}
}

(There are of course other ways, but they all make the code less readable.)

I realize that this could potentially be problematic to correct. I could 
live with the workaround, especially if it is anything but trivial to fix.

I see this as an interesting case of where DMD issues an error for valid 
code, where a typical C compiler at most would issue a warning. The 
generated code (with or without const folding) will be correct. I would 
like to hear why DMD considers the above an error while for instance 
functions without return values are not.

/Oskar



More information about the Digitalmars-d mailing list