Starting a For loop at (-1)

Nov 4, 2011 at 3:55am
Is there any reason that I can't start a For loop at (-1), rather than the usual choices of 0 or 1 (or any other positive integer)? I'm not getting an error message, but I am getting weird results when using the index as an array reference. I'm not going out of bounds or anything. The index is just used as an offset, so I know that I am within bounds.

This is a project where we have to speed up code as fast as possible, so I'm trying to get as much math out of the inner loop as I can. By starting the loop at -1, I don't have to subtract 1 with each array reference in the loop.

Here is some code:

1
2
3
4
5
for (int i = (-1); i < 2; i++) {
  val0 = val0 + myArray[row + i];
  val1 = val1 + myArray[row + i];
  val2 = val2 + myArray[row + i];
}


Nov 4, 2011 at 5:38am
I don't see why you don't just start i at 0. And what is row?
Nov 4, 2011 at 5:44am
That looks fine to me. I'm guessing you actually ARE going out of bounds there if you are getting weird errors like that...recheck your code to make sure.
Nov 4, 2011 at 6:27am
Thanks!
Topic archived. No new replies allowed.