Joan Venge
Joan Venge

Reputation: 331062

Is the condition in a for loop evaluated each iteration?

When you do stuff like:

for (int i = 0; i < collection.Count; ++i )

is collection.Count called on every iteration?

Would the result change if the Count property dynamically gets the count on call?

Upvotes: 40

Views: 12533

Answers (5)

Jonathan Allen
Jonathan Allen

Reputation: 70317

Side note, this is NOT checked for every interation in VB.

Unlike C#, VB caches the result of the collection.Count.

EDIT:

The literal VB version of the C# for loop is:

Dim i = 0
Do While i < collection.Count
    'code goes here
    i+=1
Loop

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273274

Like the other answers here: Yes, in principal.

There is (at least) one noticeable exception, array.Length. In

for (int i = 0; i < a.Length; i++) a[i] = ...;

The Length property will only be evaluated once. This is a optimization that is hardwired into the compiler. There might be others like that (in the future) but only if it is guaranteed not to make a difference in observable behavior.

Upvotes: 4

JaredPar
JaredPar

Reputation: 754763

Yes Count will be evaluated on every single pass. The reason why is that it's possible for the collection to be modified during the execution of a loop. Given the loop structure the variable i should represent a valid index into the collection during an iteration. If the check was not done on every loop then this is not provably true. Example case

for ( int i = 0; i < collection.Count; i++ ) {
  collection.Clear();
}

The one exception to this rule is looping over an array where the constraint is the Length.

for ( int i = 0; i < someArray.Length; i++ ) {
  // Code
}

The CLR JIT will special case this type of loop, in certain circumstances, since the length of an array can't change. In those cases, bounds checking will only occur once.

Reference: http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx

Upvotes: 34

Kelsey
Kelsey

Reputation: 47726

Yes count is checked at every call from the first iteration after the initialization of i to the last iteration where the check fails and the for loop is exited. You can modify the collections count if you want but realize you could end up in an endless loop.

Upvotes: 4

Jeff Martin
Jeff Martin

Reputation: 11022

Count would be evaluated on every pass. If you continued to add to the collection and the iterator never caught up, you would have an endless loop.

class Program
    {
        static void Main(string[] args)
        {
            List<int> intCollection = new List<int>();
            for(int i=-1;i < intCollection.Count;i++)
            {
                intCollection.Add(i + 1);
            }
        }
    }

This eventually will get an out of memory exception.

Upvotes: 16

Related Questions