tags:

views:

366

answers:

2
array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for each(int i in ints)
    if(i % 2 == 0)
        Debug::WriteLine("Even\n");
    else
        Debug::WriteLine("Odd\n");

Why does the above fail to compile? It works fine if I use a for(int i; ...) or if I enclose the if-else within braces. I know that the manual clearly indicates that braces are required, but I want to know why this departure from expected behaviour?

A: 

I'm not a CLI export but I believe that for each (i in ints) is what you are after.

Edit

I checked the C++ source that I have available and we are using:

for each (int i in ints) {
   // body
}

Is it possible that the braces are required? I don't have an MSFT compiler handy or I would try the following:

for each (int i in ints) {
    if(i % 2 == 0) {
        Debug::WriteLine("Even\n");
    } else {
        Debug::WriteLine("Odd\n");
    }
}
D.Shawley
This change would simply introduce (another) syntax error.
Bradley Grainger
Yup... sorry... I am too used to other languages.
D.Shawley
Actually, no, it does not introduce another syntax error - it compiles fine for me here using VS2008.
Pavel Minaev
The code was probably edited to be correct before you tried it :)
Jason Miesionczek
+1  A: 

I can't find any official documentation on it, but I can confirm the behavior you're seeing. It simply appears that the compiler is overly aggressive about finding the single statement following the for each, to the point of splitting the else from the if. It compiles it as if you had written the following, which is clearly incorrect.

array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for each(int i in ints)
{
    if(i % 2 == 0)
        Debug::WriteLine("Even\n");
}
else
    Debug::WriteLine("Odd\n");

This is obviously different to how a regular C++ for loop behaves, so you may wish to file a bug at http://connect.microsoft.com.

Bradley Grainger