Should one use < or <= in a for loop

Posted by Eugene Katz on Stack Overflow See other posts from Stack Overflow or by Eugene Katz
Published on 2008-10-08T12:59:56Z Indexed on 2010/05/07 16:38 UTC
Read the original article Hit count: 358

If you had to iterate through a loop 7 times, would you use:

for (int i = 0; i < 7; i++)

or:

for (int i = 0; i <= 6; i++)

There are two considerations:

  • performance
  • readability

For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which.

For readability I'm assuming 0-based arrays.

UPD: My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop.

There is a good point below about using a constant to which would explain what this magic number is. So if I had "int NUMBER_OF_THINGS = 7" then "i <= NUMBER_OF_THINGS - 1" would look weird, wouldn't it.

© Stack Overflow or respective owner

Related posts about Performance

Related posts about readability