Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are your tips for keeping track and avoiding bugs in loops?
    text
    copied!<p>I just found ... AGAIN ... a real time wastage bug as follows</p> <pre><code>for (int i = 0; i &lt; length; i++) { //...Lots of code for (int j = 0; i &lt; length; j++) { //...Lots of code } } </code></pre> <p>Did you notice straight ahead the inner i which SHOULD BE j ? Neither did I. So from now on I am going to use: </p> <pre><code>for (int i = 0; i &lt; length; i++) { for (int i1 = 0; i1 &lt; length; i1++) { } } </code></pre> <p>What are your tips for inner and outer while and for loops ?</p> <p>Edit: Thanks for the valuable responses. Herewith short summary of the proposed tips:</p> <ul> <li>use meaningful variables names for index variables ( instead i use SomeObjCollectionLength )</li> <li>place the contents of the inner loop into a separate method and call that method from the outer loop </li> <li>not manageable amount of lines of code between the outer and inner loop is a strong signal for code smell</li> <li>avoid copy pasting and rushing , write the index vars with care </li> </ul> <p>You might want to check the summary by <a href="https://stackoverflow.com/users/91671/lbushkin">LBushkin</a> for the <a href="https://stackoverflow.com/questions/1011712/what-are-your-tips-for-keeping-track-and-avoiding-bugs-in-loops/1015064#1015064">following</a></p> <ul> <li>use foreach and iterators whenever possible </li> <li>initialize the variables just before entering the loops</li> <li>Make each loop perform only one function. Avoid mixing responsibilities in a single loop</li> <li>When possible, make your loops short enough to view all at once</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload