Loop starting from 0 or 1? Which one and why?

10,422

Arrays of all forms in C++ are zero-based. I.e. their index start at zero and goes up to the size of the array minus one. For example an array of five elements will have the indexes 0 to 4 (inclusive).

That is why most loops in C++ are starting at zero.


As for your specific list of questions, for 1 there might be a performance difference. If you start a loop at 1 then you might need to subtract 1 in each iterator if you use the value as an array index. Or if you increase the size of the arrays then you use more memory.

For 2 it really depends on what you're iterating over. Is it over array indexes, then the loop starting at zero is clearly better. But you might need to start a loop at any value, it really depends on what you're doing and the problem you're trying to solve.

For 3, what you need to consider is what you're using the loop for.

And 4, maybe a little. ;)

Share:
10,422
Ali
Author by

Ali

Updated on June 25, 2022

Comments

  • Ali
    Ali almost 2 years

    Most of the for loops I have read/written start from 0 and to be fair most of the code I have read are used for embedded systems and they were in C/C++. In embedded systems the readability is not as important as code efficiency in some cases. Therefore, I am not sure which of the following cases would be a better choice:

    version 1

    for(i = 0; i < allowedNumberOfIteration; i++)
    {
    //something that may take from 1 iteration to allowedNumberOfIteration before it happens
      if(somethingHappened)
      {
         if(i + 1 > maxIteration)
         {
           maxIteration = i + 1;
         }
      }
    }
    

    Version 2

    for(i = 1; i <= allowedNumberOfIteration; i++)
    {
    //something that may take from 1 iteration to allowedNumberOfIteration before it happens
      if(somethingHappened)
      {
         if(i > maxIteration)
         {
           maxIteration = i;
         }
      }
    }
    

    Why first version is better in my opinion:

    1.Most loops starts with 0. So, maybe experienced programmers find it to be better if it starts from 0.

    Why second version is better in my opinion:

    1. To be fair if there was an array in the function starting from 0 would be great because the index of arrays start from zero. But in this part of the code no arrays are used.

    2. Beside the second version looks simpler because you do not have to think about the '+1'.

    Things I do not know

    1) Is there any performance difference?

    2) Which version is better?

    3) Are there any other aspect that should be considered in deciding the starting point?

    4) Am I worrying too much?