digitalmars.D.learn - array length is an unsigned value
- Derek Parnell (38/38) Mar 29 2005 Here is trap for young players ...
Here is trap for young players ... int find(dchar[] ToScan, dchar[] ToFind) { for( int lPos = 0; lPos <= (ToScan.length - ToFind.length); lPos++) { if (ToScan[lPos .. lPos + ToFind.length] == ToFind) return lPos; } return -1; } See the bug? Neither did I until I tested it with ... assert( find("xxx", "abcdef") == -1); The problem is that the expression ("xxx".length - "abcdef".length) is *not* a negative number. And thus it failed to exit the 'for' loop cleanly; instead it crashed with an ArrayBoundsError! So now I've got ... int find(dchar[] ToScan, dchar[] ToFind) { if (ToScan.length == 0) return -1; if (ToFind.length == 0) return -1; if (ToFind.length > ToScan.length) return -1; for( int lPos = 0; lPos <= (ToScan.length - ToFind.length); lPos++) { if (ToScan[lPos .. lPos + ToFind.length] == ToFind) return lPos; } return -1; } Oh well, live and learn. -- Derek Parnell Melbourne, Australia http://www.dsource.org/projects/build/ http://www.prowiki.org/wiki4d/wiki.cgi?FrontPage 30/03/2005 10:34:52 AM
Mar 29 2005