The C++ "for each" syntax

For Each? I won't go into a huge justification - suffice to say, there are some instances where it is nice to be able to iterate over a set, and perform operations on each member of that set. A good primer might be the MSDN node on C# foreach.

A basic sample. If you're familiar with C++ for statements or the C# foreach statement, the C++ for each statement should be fairly familiar. I'll steal from a C# sample, and convert to C++:

using namespace System;

int main(){
array<int>^ arr = gcnew array<int>{0,1,2,5,7,8,11};
int even=0, odd=0;

  for each (int i in arr) {
if (i%2 == 0)

  Console::WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
odd, even);

Pretty simple. There are some definite advantages to for each. Most importantly, it beats struggling with iterators and IEnumerables almost any day of the week. There are also some interesting things you can do with for each. For example, you can do fun things like for each(Char c in "abcdefg"). Go crazy with Generic Collections. And, here's a code sample that I know will make some of you out there salivate:

#include <vector>
#include <iostream>
using namespace std;

int main() {
int total = 0;

  vector<int> v(6);
v[0] = 10; v[1] = 20; v[2] = 30;
v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
total += i;

cout << total << endl;

Here's the kicker: you can compile the above natively. Why throw in the CLR if you don't want to? Of course, it compiles just fine with the CLR, but for each works on any STL-compliant container in native C++. Now that's a compiler improvement I can get behind. Next time, I'll take a first look at DF. I think it's going to take me a few posts to get it sorted out.