Out of bound problem

Denton Cockburn diboss at hotmail.com
Sat Feb 16 18:56:38 PST 2008


On Sun, 17 Feb 2008 11:37:53 +0900, Neil Vice wrote:

> "bearophile" <bearophileHUGS at lycos.com> wrote in message
> news:fp800a$2781$1 at digitalmars.com...
>> While testing I have found a problem in my code, I have reduced the
>> code to the following lines:
>>
>> template IsArray(T) {
>>    const bool IsArray = is(typeof(T.length)) && is(typeof(T.sort)) &&
>>                         is(typeof(T.reverse)) && is(typeof(T.dup));
>> }
>>
>> TA[] foo(TA, TB)(TA[] a, TB b) {
>>    TA[] result;
>>
>>    static if (IsArray!(TB)) {
>>        if (b.length == 0) {
>>            result = a;
>>        } else if (b.length == 1) {
>>            result = foo(a, b[0]);
>>        }
>>    }
>>
>>    return result;
>> }
>>
>> void main() {
>>    foo("test", "");
>> }
>>
>>
>> Its output:
>>
>> bug.d(13): Error: array index 0 is out of bounds b[0 .. 0] bug.d(13):
>> Error: array index 0 is out of bounds b[0 .. 0] bug.d(13): Error: array
>> index 0 is out of bounds b[0 .. 0] bug.d(21): template instance
>> bug.foo!(char,char[0u]) error instantiating
>>
>> I have found ways to solve this problem, but can someone please explain
>> me what's the problem?
>>
>> Bye and thank you,
>> bearophile
> 
> As far as I can tell the cause is that the expression b[0] is being
> evaluated even if the enclosing if statement hasn't been entered. For
> example if the line containing b[0] is replaced with a writef() it is
> never output to the console.
> 
> I can only assume that this is a compiler bug.

Behaviour exists in DMD 2.010 and GDC 0.25(1.021)
 


More information about the Digitalmars-d-learn mailing list