Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the condition in a for loop evaluated each iteration?

Tags:

c#

.net

loops

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?

like image 952
Joan Venge Avatar asked Mar 17 '09 17:03

Joan Venge


People also ask

Does for loop check condition every time?

Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.

What is the condition in a for loop?

Condition is an expression that is tested each time the loop repeats. As long as condition is true, the loop keeps running. Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true).

Is evaluated only once when the for loop starts in C#?

Note: Initialization part is evaluated only once when the for loop starts. Example: // C# program to illustrate for loop.

How many conditions do you need for a for loop?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.


2 Answers

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

like image 190
JaredPar Avatar answered Sep 24 '22 08:09

JaredPar


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.

like image 33
Jeff Martin Avatar answered Sep 24 '22 08:09

Jeff Martin