Var inside the FOR when starting at 0(zero) Count should be Count-1?

Asked

Viewed 408 times

3

I picked up a system at the company where I work for another colleague. I note that all FOR’s are like this:

for(int i = 0; i < lista.count; i++)
{
  //meu código
}

I learned that when a variable inside the FOR starts with zero, man COUNT should always be Count - 1, unless there is a specific rule for this to occur. I am sure?

1 answer

7


Yes, you’re right, it’s basic math. If you have 10 elements, and you start counting from 0 to 9: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

The Count tells you how many elements you have in the list. Then you should count to the pre-count element using Count - 1.

Unless you have some reason to use it differently but usually there is no reason why and even if there is, it would have to be an even lower value. Certainly if you try to access a number element equal to count will generate an exception.

Note the "equal" highlight up there. This is true if you are using the comparison operator <=.

In your example you are using the <, then there’s no need to do the -1. 'Cause he’s gonna stop an element before it’s over.

See this code demonstrated the difference:

using static System.Console;
using System.Collections.Generic;
                    
public class Program {
    public static void Main() {
        var lista = new List<int>();
        for (var i = 0; i < 10; i++) lista.Add(i);
        for (var i = 0; i < lista.Count; i++) WriteLine(lista[i]);
        for (var i = 0; i <= lista.Count - 1; i++) WriteLine(lista[i]);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

When you use the <= one more element is caught because of the same. The < takes everyone who’s a minor, but <= takes everyone who is smaller plus the element that is equal.

In general I prefer the first one, has one less mathematical operation to do. Not that it necessarily means it’s faster, only it’s simpler. As I demonstrated in that other answer, what everyone expects can be false and only testing to state which is faster. Can be that making a "smaller or equal" is slower than making a "smaller" and a "subtraction".

Another detail that may be just a typo is that the property that shows the number of elements in the list is Count. Is not COUNT and it’s not count.

Certainly I would use a foreach in this case and I wouldn’t worry about it. I’ve already shown in the answer linked above that it is equal to or better than the for in performance and is simpler. In addition to being semantically more correct. The for above is saying to pick up all the elements, which is exactly the reason for the foreach exist. And it ensures that everything will be right in the process. It is simpler in every way. The for would only be useful if it is important to have an element index number in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.