Seems like it would fix the off by one error that happens a lot, but can you use a variable in that? Like object?
(Speaking from a C# standpoint:)
foreach is just as versatile as a for loop.
When most people learn for loops, they learn syntax like:
for (int i=0; i < 10; i++) { /* Something */ }
However, a for loop is way more versatile than a counter such as that. Each one of the statements in the for loops 'arguements' (Not what it's called, but I'm unaware of the actual naming), is a statement, each executed at a different time:
for ( A; B; C)
A - Executed before the loop. The 'initialization'. Variables declared here are local to the scope of the for loop.
B - Exit Condition. While this statement resolves to non-zero, the loop will continue.
C - Update. Normally used to push a condition closer to pushing out of the loop (Making B resolve false).
You could re-write that first for loop as a while loop, such as:
int i = 0;
while (i < 10)
{
//Do something.
i++;
}
And that has all three parts, initialization, update, and exit condition, illustrated here:
A;
while (B)
{
//Do something.
C;
}
Knowing the structure of how loops such as this execute lets you do a lot fancier things. Such as, people use this for an infinite loop:
while(1) {}
That can be done the same way with a for loop:
for(;;) {}
A blank statement initializes, a blank statement updates, and theres no exit condition, so it continues forever.
How does this all relate to a foreach loop?
A for each essentially takes care of doing A, B, and C for you, assumed from one statement. You could roll out any foreach loop into a for (or any other, for that matter) loop. Take the following C# foreach:
foreach (String s in lStringList)
{
Console.WriteLine(s);
}
Now lets see what's happening, if it were written out in a traditional for loop:
for (int i = 0; i < lStringList.Count; i++)
{
String s = lStringList[i];
Console.WriteLine(s);
}
Both would provide the exact same output.
For the curious, here's a little sample code that prints out what I illustrated above. (A C# Console App)
using System;
using System.Collections.Generic;
using System.Text;
namespace consoleappcsharp
{
class Program
{
static void Main(string[] args)
{
//Make a new list that holds strings.
List<String> lStringList = new List<String>();
//Add three test strings.
lStringList.Add("Test String 1");
lStringList.Add("Test String 2");
lStringList.Add("Test String 3");
//A foreach loop that prints each test string.
Console.WriteLine("foreach (String s in lStringList)\n");
foreach (String s in lStringList)
{
Console.WriteLine(s);
}
//A for loop that mimics the same thing as the above foreach
Console.WriteLine("\n\nfor(int i = 0; i < lStringList.Count; i++)\n");
for (int i = 0; i < lStringList.Count; i++ )
{
String s = lStringList[i];
Console.WriteLine(s);
}
}
}
}
Sorry if I got a bit long winded, I just enjoy this stuff