Hacker News new | ask | show | jobs
by pmontra 3692 days ago
It doesn't apply to that sample code but maybe this is generally safer:

   for (pos = 0; !found || pos < limit; pos++)
but there is nothing wrong in using an iterator and break out of the loop, especially if the language or the library gives you iterators.
1 comments

That should be logical AND, not logical OR, because if you go over the limit and the right side is False, the left side will always be True if the item is not found, and True || False is still True, and the loop continues infinitely.

When you are over the iteration limit you want to trigger True && False which is False to break out of the loop where the right side False is the condition when pos > limit

Btw this is covered in Code Complete Second Edition by Microsoft Press on page 378-380

You are right. I believed I didn't need a test for that. See what happens? :-)