char[] annoyance...

S. Chancellor dnewsgr at mephit.kicks-ass.org
Mon Apr 10 00:54:25 PDT 2006


On 2006-04-10 00:50:24 -0700, S. Chancellor 
<dnewsgr at mephit.kicks-ass.org> said:

> On 2006-04-09 17:23:06 -0700, "Regan Heath" <regan at netwin.co.nz> said:
> 
>> Take this code:
>> 
>> void main()
>> {
>> 	//..open a file, read line for line, on each line:
>> 
>> 	for(int i = 0; i < line.length-2; i++) {
>> 		if (line[i..i+2] != "||") continue;
>> 		//..etc..
>> 	}
>> }
>> 
>> 
>> There is a subtle bug. On all lines with a length of 0 or 1 it will 
>> give  the following error:
>> 
>> Error: ArrayBoundsError line_length.d(6)
>> 
>> 
>> The problem is of course the statement "i < line.length-2". line.length 
>> is  unsigned, and when you - 2 from an unsigned value.. well lets just 
>> say  that it's bigger than the actual length of the line - 2.
>> 
>> 
>> Of course there are plently of other ways to code this, perhaps using  
>> foreach, but that's not the point. The point is that this code  _can_ 
>> be  written and on the surface looks fine. Not even -w (warnings) spots 
>> the  signed/unsigned problem. At the very least can we get a warning 
>> for this?
>> 
>> Regan
> 
> 
> if( line[i.. (i+2 > $ ? $ : i +2 ) ] != "||")
> {
> 	...
> }
> 
> Is that not allowed in the [..] syntax?
> 
> -S.

Erps, I should skim your post better.  Yeah that's a problem, you can 
fix it without the other if though.

for(int i = 0; i + 2 < line.length; i++) {


Or am I still missing something?  Hehe.

-S




More information about the Digitalmars-d mailing list